clang 15.0.7
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
21#include "clang/AST/ExprCXX.h"
25#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/Lookup.h"
38#include "clang/Sema/Scope.h"
41#include "clang/Sema/Template.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/StringExtras.h"
46#include <map>
47#include <set>
48
49using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// CheckDefaultArgumentVisitor
53//===----------------------------------------------------------------------===//
54
55namespace {
56/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57/// the default argument of a parameter to determine whether it
58/// contains any ill-formed subexpressions. For example, this will
59/// diagnose the use of local variables or parameters within the
60/// default argument expression.
61class CheckDefaultArgumentVisitor
62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63 Sema &S;
64 const Expr *DefaultArg;
65
66public:
67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68 : S(S), DefaultArg(DefaultArg) {}
69
70 bool VisitExpr(const Expr *Node);
71 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73 bool VisitLambdaExpr(const LambdaExpr *Lambda);
74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75};
76
77/// VisitExpr - Visit all of the children of this expression.
78bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79 bool IsInvalid = false;
80 for (const Stmt *SubStmt : Node->children())
81 IsInvalid |= Visit(SubStmt);
82 return IsInvalid;
83}
84
85/// VisitDeclRefExpr - Visit a reference to a declaration, to
86/// determine whether this declaration can be used in the default
87/// argument expression.
88bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89 const NamedDecl *Decl = DRE->getDecl();
90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91 // C++ [dcl.fct.default]p9:
92 // [...] parameters of a function shall not be used in default
93 // argument expressions, even if they are not evaluated. [...]
94 //
95 // C++17 [dcl.fct.default]p9 (by CWG 2082):
96 // [...] A parameter shall not appear as a potentially-evaluated
97 // expression in a default argument. [...]
98 //
99 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100 return S.Diag(DRE->getBeginLoc(),
101 diag::err_param_default_argument_references_param)
102 << Param->getDeclName() << DefaultArg->getSourceRange();
103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104 // C++ [dcl.fct.default]p7:
105 // Local variables shall not be used in default argument
106 // expressions.
107 //
108 // C++17 [dcl.fct.default]p7 (by CWG 2082):
109 // A local variable shall not appear as a potentially-evaluated
110 // expression in a default argument.
111 //
112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113 // Note: A local variable cannot be odr-used (6.3) in a default argument.
114 //
115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116 return S.Diag(DRE->getBeginLoc(),
117 diag::err_param_default_argument_references_local)
118 << VDecl->getDeclName() << DefaultArg->getSourceRange();
119 }
120
121 return false;
122}
123
124/// VisitCXXThisExpr - Visit a C++ "this" expression.
125bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126 // C++ [dcl.fct.default]p8:
127 // The keyword this shall not be used in a default argument of a
128 // member function.
129 return S.Diag(ThisE->getBeginLoc(),
130 diag::err_param_default_argument_references_this)
131 << ThisE->getSourceRange();
132}
133
134bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135 const PseudoObjectExpr *POE) {
136 bool Invalid = false;
137 for (const Expr *E : POE->semantics()) {
138 // Look through bindings.
139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140 E = OVE->getSourceExpr();
141 assert(E && "pseudo-object binding without source expression?");
142 }
143
144 Invalid |= Visit(E);
145 }
146 return Invalid;
147}
148
149bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150 // C++11 [expr.lambda.prim]p13:
151 // A lambda-expression appearing in a default argument shall not
152 // implicitly or explicitly capture any entity.
153 if (Lambda->capture_begin() == Lambda->capture_end())
154 return false;
155
156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157}
158} // namespace
159
160void
162 const CXXMethodDecl *Method) {
163 // If we have an MSAny spec already, don't bother.
164 if (!Method || ComputedEST == EST_MSAny)
165 return;
166
167 const FunctionProtoType *Proto
168 = Method->getType()->getAs<FunctionProtoType>();
169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170 if (!Proto)
171 return;
172
174
175 // If we have a throw-all spec at this point, ignore the function.
176 if (ComputedEST == EST_None)
177 return;
178
179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180 EST = EST_BasicNoexcept;
181
182 switch (EST) {
183 case EST_Unparsed:
185 case EST_Unevaluated:
186 llvm_unreachable("should not see unresolved exception specs here");
187
188 // If this function can throw any exceptions, make a note of that.
189 case EST_MSAny:
190 case EST_None:
191 // FIXME: Whichever we see last of MSAny and None determines our result.
192 // We should make a consistent, order-independent choice here.
193 ClearExceptions();
194 ComputedEST = EST;
195 return;
197 ClearExceptions();
198 ComputedEST = EST_None;
199 return;
200 // FIXME: If the call to this decl is using any of its default arguments, we
201 // need to search them for potentially-throwing calls.
202 // If this function has a basic noexcept, it doesn't affect the outcome.
204 case EST_NoexceptTrue:
205 case EST_NoThrow:
206 return;
207 // If we're still at noexcept(true) and there's a throw() callee,
208 // change to that specification.
209 case EST_DynamicNone:
210 if (ComputedEST == EST_BasicNoexcept)
211 ComputedEST = EST_DynamicNone;
212 return;
214 llvm_unreachable(
215 "should not generate implicit declarations for dependent cases");
216 case EST_Dynamic:
217 break;
218 }
219 assert(EST == EST_Dynamic && "EST case not considered earlier.");
220 assert(ComputedEST != EST_None &&
221 "Shouldn't collect exceptions when throw-all is guaranteed.");
222 ComputedEST = EST_Dynamic;
223 // Record the exceptions in this function's exception specification.
224 for (const auto &E : Proto->exceptions())
225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226 Exceptions.push_back(E);
227}
228
230 if (!S || ComputedEST == EST_MSAny)
231 return;
232
233 // FIXME:
234 //
235 // C++0x [except.spec]p14:
236 // [An] implicit exception-specification specifies the type-id T if and
237 // only if T is allowed by the exception-specification of a function directly
238 // invoked by f's implicit definition; f shall allow all exceptions if any
239 // function it directly invokes allows all exceptions, and f shall allow no
240 // exceptions if every function it directly invokes allows no exceptions.
241 //
242 // Note in particular that if an implicit exception-specification is generated
243 // for a function containing a throw-expression, that specification can still
244 // be noexcept(true).
245 //
246 // Note also that 'directly invoked' is not defined in the standard, and there
247 // is no indication that we should only consider potentially-evaluated calls.
248 //
249 // Ultimately we should implement the intent of the standard: the exception
250 // specification should be the set of exceptions which can be thrown by the
251 // implicit definition. For now, we assume that any non-nothrow expression can
252 // throw any exception.
253
254 if (Self->canThrow(S))
255 ComputedEST = EST_None;
256}
257
259 SourceLocation EqualLoc) {
260 if (RequireCompleteType(Param->getLocation(), Param->getType(),
261 diag::err_typecheck_decl_incomplete_type))
262 return true;
263
264 // C++ [dcl.fct.default]p5
265 // A default argument expression is implicitly converted (clause
266 // 4) to the parameter type. The default argument expression has
267 // the same semantic constraints as the initializer expression in
268 // a declaration of a variable of the parameter type, using the
269 // copy-initialization semantics (8.5).
271 Param);
272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273 EqualLoc);
274 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276 if (Result.isInvalid())
277 return true;
278 Arg = Result.getAs<Expr>();
279
280 CheckCompletedExpr(Arg, EqualLoc);
281 Arg = MaybeCreateExprWithCleanups(Arg);
282
283 return Arg;
284}
285
287 SourceLocation EqualLoc) {
288 // Add the default argument to the parameter
289 Param->setDefaultArg(Arg);
290
291 // We have already instantiated this parameter; provide each of the
292 // instantiations with the uninstantiated default argument.
293 UnparsedDefaultArgInstantiationsMap::iterator InstPos
294 = UnparsedDefaultArgInstantiations.find(Param);
295 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
299 // We're done tracking this parameter's instantiations.
300 UnparsedDefaultArgInstantiations.erase(InstPos);
301 }
302}
303
304/// ActOnParamDefaultArgument - Check whether the default argument
305/// provided for a function parameter is well-formed. If so, attach it
306/// to the parameter declaration.
307void
309 Expr *DefaultArg) {
310 if (!param || !DefaultArg)
311 return;
312
313 ParmVarDecl *Param = cast<ParmVarDecl>(param);
314 UnparsedDefaultArgLocs.erase(Param);
315
316 auto Fail = [&] {
317 Param->setInvalidDecl();
318 Param->setDefaultArg(new (Context) OpaqueValueExpr(
319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320 };
321
322 // Default arguments are only permitted in C++
323 if (!getLangOpts().CPlusPlus) {
324 Diag(EqualLoc, diag::err_param_default_argument)
325 << DefaultArg->getSourceRange();
326 return Fail();
327 }
328
329 // Check for unexpanded parameter packs.
330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331 return Fail();
332 }
333
334 // C++11 [dcl.fct.default]p3
335 // A default argument expression [...] shall not be specified for a
336 // parameter pack.
337 if (Param->isParameterPack()) {
338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339 << DefaultArg->getSourceRange();
340 // Recover by discarding the default argument.
341 Param->setDefaultArg(nullptr);
342 return;
343 }
344
345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346 if (Result.isInvalid())
347 return Fail();
348
349 DefaultArg = Result.getAs<Expr>();
350
351 // Check that the default argument is well-formed
352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353 if (DefaultArgChecker.Visit(DefaultArg))
354 return Fail();
355
356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357}
358
359/// ActOnParamUnparsedDefaultArgument - We've seen a default
360/// argument for a function parameter, but we can't parse it yet
361/// because we're inside a class definition. Note that this default
362/// argument will be parsed later.
364 SourceLocation EqualLoc,
365 SourceLocation ArgLoc) {
366 if (!param)
367 return;
368
369 ParmVarDecl *Param = cast<ParmVarDecl>(param);
370 Param->setUnparsedDefaultArg();
371 UnparsedDefaultArgLocs[Param] = ArgLoc;
372}
373
374/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375/// the default argument for the parameter param failed.
377 SourceLocation EqualLoc) {
378 if (!param)
379 return;
380
381 ParmVarDecl *Param = cast<ParmVarDecl>(param);
382 Param->setInvalidDecl();
383 UnparsedDefaultArgLocs.erase(Param);
384 Param->setDefaultArg(new (Context) OpaqueValueExpr(
385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386}
387
388/// CheckExtraCXXDefaultArguments - Check for any extra default
389/// arguments in the declarator, which is not a function declaration
390/// or definition and therefore is not permitted to have default
391/// arguments. This routine should be invoked for every declarator
392/// that is not a function declaration or definition.
394 // C++ [dcl.fct.default]p3
395 // A default argument expression shall be specified only in the
396 // parameter-declaration-clause of a function declaration or in a
397 // template-parameter (14.1). It shall not be specified for a
398 // parameter pack. If it is specified in a
399 // parameter-declaration-clause, it shall not occur within a
400 // declarator or abstract-declarator of a parameter-declaration.
401 bool MightBeFunction = D.isFunctionDeclarationContext();
402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403 DeclaratorChunk &chunk = D.getTypeObject(i);
404 if (chunk.Kind == DeclaratorChunk::Function) {
405 if (MightBeFunction) {
406 // This is a function declaration. It can have default arguments, but
407 // keep looking in case its return type is a function type with default
408 // arguments.
409 MightBeFunction = false;
410 continue;
411 }
412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413 ++argIdx) {
414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415 if (Param->hasUnparsedDefaultArg()) {
416 std::unique_ptr<CachedTokens> Toks =
417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418 SourceRange SR;
419 if (Toks->size() > 1)
420 SR = SourceRange((*Toks)[1].getLocation(),
421 Toks->back().getLocation());
422 else
423 SR = UnparsedDefaultArgLocs[Param];
424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425 << SR;
426 } else if (Param->getDefaultArg()) {
427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428 << Param->getDefaultArg()->getSourceRange();
429 Param->setDefaultArg(nullptr);
430 }
431 }
432 } else if (chunk.Kind != DeclaratorChunk::Paren) {
433 MightBeFunction = false;
434 }
435 }
436}
437
439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441 });
442}
443
444/// MergeCXXFunctionDecl - Merge two declarations of the same C++
445/// function, once we already know that they have the same
446/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447/// error, false otherwise.
449 Scope *S) {
450 bool Invalid = false;
451
452 // The declaration context corresponding to the scope is the semantic
453 // parent, unless this is a local function declaration, in which case
454 // it is that surrounding function.
455 DeclContext *ScopeDC = New->isLocalExternDecl()
456 ? New->getLexicalDeclContext()
457 : New->getDeclContext();
458
459 // Find the previous declaration for the purpose of default arguments.
460 FunctionDecl *PrevForDefaultArgs = Old;
461 for (/**/; PrevForDefaultArgs;
462 // Don't bother looking back past the latest decl if this is a local
463 // extern declaration; nothing else could work.
464 PrevForDefaultArgs = New->isLocalExternDecl()
465 ? nullptr
466 : PrevForDefaultArgs->getPreviousDecl()) {
467 // Ignore hidden declarations.
468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469 continue;
470
471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472 !New->isCXXClassMember()) {
473 // Ignore default arguments of old decl if they are not in
474 // the same scope and this is not an out-of-line definition of
475 // a member function.
476 continue;
477 }
478
479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480 // If only one of these is a local function declaration, then they are
481 // declared in different scopes, even though isDeclInScope may think
482 // they're in the same scope. (If both are local, the scope check is
483 // sufficient, and if neither is local, then they are in the same scope.)
484 continue;
485 }
486
487 // We found the right previous declaration.
488 break;
489 }
490
491 // C++ [dcl.fct.default]p4:
492 // For non-template functions, default arguments can be added in
493 // later declarations of a function in the same
494 // scope. Declarations in different scopes have completely
495 // distinct sets of default arguments. That is, declarations in
496 // inner scopes do not acquire default arguments from
497 // declarations in outer scopes, and vice versa. In a given
498 // function declaration, all parameters subsequent to a
499 // parameter with a default argument shall have default
500 // arguments supplied in this or previous declarations. A
501 // default argument shall not be redefined by a later
502 // declaration (not even to the same value).
503 //
504 // C++ [dcl.fct.default]p6:
505 // Except for member functions of class templates, the default arguments
506 // in a member function definition that appears outside of the class
507 // definition are added to the set of default arguments provided by the
508 // member function declaration in the class definition.
509 for (unsigned p = 0, NumParams = PrevForDefaultArgs
510 ? PrevForDefaultArgs->getNumParams()
511 : 0;
512 p < NumParams; ++p) {
513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514 ParmVarDecl *NewParam = New->getParamDecl(p);
515
516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517 bool NewParamHasDfl = NewParam->hasDefaultArg();
518
519 if (OldParamHasDfl && NewParamHasDfl) {
520 unsigned DiagDefaultParamID =
521 diag::err_param_default_argument_redefinition;
522
523 // MSVC accepts that default parameters be redefined for member functions
524 // of template class. The new default parameter's value is ignored.
525 Invalid = true;
526 if (getLangOpts().MicrosoftExt) {
527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528 if (MD && MD->getParent()->getDescribedClassTemplate()) {
529 // Merge the old default argument into the new parameter.
530 NewParam->setHasInheritedDefaultArg();
531 if (OldParam->hasUninstantiatedDefaultArg())
533 OldParam->getUninstantiatedDefaultArg());
534 else
535 NewParam->setDefaultArg(OldParam->getInit());
536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537 Invalid = false;
538 }
539 }
540
541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542 // hint here. Alternatively, we could walk the type-source information
543 // for NewParam to find the last source location in the type... but it
544 // isn't worth the effort right now. This is the kind of test case that
545 // is hard to get right:
546 // int f(int);
547 // void g(int (*fp)(int) = f);
548 // void g(int (*fp)(int) = &f);
549 Diag(NewParam->getLocation(), DiagDefaultParamID)
550 << NewParam->getDefaultArgRange();
551
552 // Look for the function declaration where the default argument was
553 // actually written, which may be a declaration prior to Old.
554 for (auto Older = PrevForDefaultArgs;
555 OldParam->hasInheritedDefaultArg(); /**/) {
556 Older = Older->getPreviousDecl();
557 OldParam = Older->getParamDecl(p);
558 }
559
560 Diag(OldParam->getLocation(), diag::note_previous_definition)
561 << OldParam->getDefaultArgRange();
562 } else if (OldParamHasDfl) {
563 // Merge the old default argument into the new parameter unless the new
564 // function is a friend declaration in a template class. In the latter
565 // case the default arguments will be inherited when the friend
566 // declaration will be instantiated.
567 if (New->getFriendObjectKind() == Decl::FOK_None ||
569 // It's important to use getInit() here; getDefaultArg()
570 // strips off any top-level ExprWithCleanups.
571 NewParam->setHasInheritedDefaultArg();
572 if (OldParam->hasUnparsedDefaultArg())
573 NewParam->setUnparsedDefaultArg();
574 else if (OldParam->hasUninstantiatedDefaultArg())
576 OldParam->getUninstantiatedDefaultArg());
577 else
578 NewParam->setDefaultArg(OldParam->getInit());
579 }
580 } else if (NewParamHasDfl) {
581 if (New->getDescribedFunctionTemplate()) {
582 // Paragraph 4, quoted above, only applies to non-template functions.
583 Diag(NewParam->getLocation(),
584 diag::err_param_default_argument_template_redecl)
585 << NewParam->getDefaultArgRange();
586 Diag(PrevForDefaultArgs->getLocation(),
587 diag::note_template_prev_declaration)
588 << false;
589 } else if (New->getTemplateSpecializationKind()
592 // C++ [temp.expr.spec]p21:
593 // Default function arguments shall not be specified in a declaration
594 // or a definition for one of the following explicit specializations:
595 // - the explicit specialization of a function template;
596 // - the explicit specialization of a member function template;
597 // - the explicit specialization of a member function of a class
598 // template where the class template specialization to which the
599 // member function specialization belongs is implicitly
600 // instantiated.
601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
603 << New->getDeclName()
604 << NewParam->getDefaultArgRange();
605 } else if (New->getDeclContext()->isDependentContext()) {
606 // C++ [dcl.fct.default]p6 (DR217):
607 // Default arguments for a member function of a class template shall
608 // be specified on the initial declaration of the member function
609 // within the class template.
610 //
611 // Reading the tea leaves a bit in DR217 and its reference to DR205
612 // leads me to the conclusion that one cannot add default function
613 // arguments for an out-of-line definition of a member function of a
614 // dependent type.
615 int WhichKind = 2;
616 if (CXXRecordDecl *Record
617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618 if (Record->getDescribedClassTemplate())
619 WhichKind = 0;
620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621 WhichKind = 1;
622 else
623 WhichKind = 2;
624 }
625
626 Diag(NewParam->getLocation(),
627 diag::err_param_default_argument_member_template_redecl)
628 << WhichKind
629 << NewParam->getDefaultArgRange();
630 }
631 }
632 }
633
634 // DR1344: If a default argument is added outside a class definition and that
635 // default argument makes the function a special member function, the program
636 // is ill-formed. This can only happen for constructors.
637 if (isa<CXXConstructorDecl>(New) &&
639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641 if (NewSM != OldSM) {
642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643 assert(NewParam->hasDefaultArg());
644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645 << NewParam->getDefaultArgRange() << NewSM;
646 Diag(Old->getLocation(), diag::note_previous_declaration);
647 }
648 }
649
650 const FunctionDecl *Def;
651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652 // template has a constexpr specifier then all its declarations shall
653 // contain the constexpr specifier.
654 if (New->getConstexprKind() != Old->getConstexprKind()) {
655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656 << New << static_cast<int>(New->getConstexprKind())
657 << static_cast<int>(Old->getConstexprKind());
658 Diag(Old->getLocation(), diag::note_previous_declaration);
659 Invalid = true;
660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661 Old->isDefined(Def) &&
662 // If a friend function is inlined but does not have 'inline'
663 // specifier, it is a definition. Do not report attribute conflict
664 // in this case, redefinition will be diagnosed later.
665 (New->isInlineSpecified() ||
667 // C++11 [dcl.fcn.spec]p4:
668 // If the definition of a function appears in a translation unit before its
669 // first declaration as inline, the program is ill-formed.
670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671 Diag(Def->getLocation(), diag::note_previous_definition);
672 Invalid = true;
673 }
674
675 // C++17 [temp.deduct.guide]p3:
676 // Two deduction guide declarations in the same translation unit
677 // for the same class template shall not have equivalent
678 // parameter-declaration-clauses.
679 if (isa<CXXDeductionGuideDecl>(New) &&
680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 }
684
685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686 // argument expression, that declaration shall be a definition and shall be
687 // the only declaration of the function or function template in the
688 // translation unit.
691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692 Diag(Old->getLocation(), diag::note_previous_declaration);
693 Invalid = true;
694 }
695
696 // C++11 [temp.friend]p4 (DR329):
697 // When a function is defined in a friend function declaration in a class
698 // template, the function is instantiated when the function is odr-used.
699 // The same restrictions on multiple declarations and definitions that
700 // apply to non-template function declarations and definitions also apply
701 // to these implicit definitions.
702 const FunctionDecl *OldDefinition = nullptr;
704 Old->isDefined(OldDefinition, true))
705 CheckForFunctionRedefinition(New, OldDefinition);
706
707 return Invalid;
708}
709
710NamedDecl *
712 MultiTemplateParamsArg TemplateParamLists) {
713 assert(D.isDecompositionDeclarator());
715
716 // The syntax only allows a decomposition declarator as a simple-declaration,
717 // a for-range-declaration, or a condition in Clang, but we parse it in more
718 // cases than that.
720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721 << Decomp.getSourceRange();
722 return nullptr;
723 }
724
725 if (!TemplateParamLists.empty()) {
726 // FIXME: There's no rule against this, but there are also no rules that
727 // would actually make it usable, so we reject it for now.
728 Diag(TemplateParamLists.front()->getTemplateLoc(),
729 diag::err_decomp_decl_template);
730 return nullptr;
731 }
732
733 Diag(Decomp.getLSquareLoc(),
734 !getLangOpts().CPlusPlus17
735 ? diag::ext_decomp_decl
736 : D.getContext() == DeclaratorContext::Condition
737 ? diag::ext_decomp_decl_cond
738 : diag::warn_cxx14_compat_decomp_decl)
739 << Decomp.getSourceRange();
740
741 // The semantic context is always just the current context.
742 DeclContext *const DC = CurContext;
743
744 // C++17 [dcl.dcl]/8:
745 // The decl-specifier-seq shall contain only the type-specifier auto
746 // and cv-qualifiers.
747 // C++2a [dcl.dcl]/8:
748 // If decl-specifier-seq contains any decl-specifier other than static,
749 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
750 auto &DS = D.getDeclSpec();
751 {
752 SmallVector<StringRef, 8> BadSpecifiers;
753 SmallVector<SourceLocation, 8> BadSpecifierLocs;
754 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756 if (auto SCS = DS.getStorageClassSpec()) {
757 if (SCS == DeclSpec::SCS_static) {
758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760 } else {
761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763 }
764 }
765 if (auto TSCS = DS.getThreadStorageClassSpec()) {
766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768 }
769 if (DS.hasConstexprSpecifier()) {
770 BadSpecifiers.push_back(
771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773 }
774 if (DS.isInlineSpecified()) {
775 BadSpecifiers.push_back("inline");
776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777 }
778 if (!BadSpecifiers.empty()) {
779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780 Err << (int)BadSpecifiers.size()
781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782 // Don't add FixItHints to remove the specifiers; we do still respect
783 // them when building the underlying variable.
784 for (auto Loc : BadSpecifierLocs)
785 Err << SourceRange(Loc, Loc);
786 } else if (!CPlusPlus20Specifiers.empty()) {
787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788 getLangOpts().CPlusPlus20
789 ? diag::warn_cxx17_compat_decomp_decl_spec
790 : diag::ext_decomp_decl_spec);
791 Warn << (int)CPlusPlus20Specifiers.size()
792 << llvm::join(CPlusPlus20Specifiers.begin(),
793 CPlusPlus20Specifiers.end(), " ");
794 for (auto Loc : CPlusPlus20SpecifierLocs)
795 Warn << SourceRange(Loc, Loc);
796 }
797 // We can't recover from it being declared as a typedef.
798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799 return nullptr;
800 }
801
802 // C++2a [dcl.struct.bind]p1:
803 // A cv that includes volatile is deprecated
804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805 getLangOpts().CPlusPlus20)
806 Diag(DS.getVolatileSpecLoc(),
807 diag::warn_deprecated_volatile_structured_binding);
808
809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810 QualType R = TInfo->getType();
811
812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813 UPPC_DeclarationType))
814 D.setInvalidType();
815
816 // The syntax only allows a single ref-qualifier prior to the decomposition
817 // declarator. No other declarator chunks are permitted. Also check the type
818 // specifier here.
819 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821 (D.getNumTypeObjects() == 1 &&
823 Diag(Decomp.getLSquareLoc(),
824 (D.hasGroupingParens() ||
825 (D.getNumTypeObjects() &&
827 ? diag::err_decomp_decl_parens
828 : diag::err_decomp_decl_type)
829 << R;
830
831 // In most cases, there's no actual problem with an explicitly-specified
832 // type, but a function type won't work here, and ActOnVariableDeclarator
833 // shouldn't be called for such a type.
834 if (R->isFunctionType())
835 D.setInvalidType();
836 }
837
838 // Build the BindingDecls.
840
841 // Build the BindingDecls.
842 for (auto &B : D.getDecompositionDeclarator().bindings()) {
843 // Check for name conflicts.
844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846 ForVisibleRedeclaration);
847 LookupName(Previous, S,
848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849
850 // It's not permitted to shadow a template parameter name.
851 if (Previous.isSingleResult() &&
852 Previous.getFoundDecl()->isTemplateParameter()) {
853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854 Previous.getFoundDecl());
855 Previous.clear();
856 }
857
858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859
860 // Find the shadowed declaration before filtering for scope.
861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862 ? getShadowedDeclaration(BD, Previous)
863 : nullptr;
864
865 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868 /*AllowInlineNamespace*/false);
869
870 if (!Previous.empty()) {
871 auto *Old = Previous.getRepresentativeDecl();
872 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873 Diag(Old->getLocation(), diag::note_previous_definition);
874 } else if (ShadowedDecl && !D.isRedeclaration()) {
875 CheckShadow(BD, ShadowedDecl, Previous);
876 }
877 PushOnScopeChains(BD, S, true);
878 Bindings.push_back(BD);
879 ParsingInitForAutoVars.insert(BD);
880 }
881
882 // There are no prior lookup results for the variable itself, because it
883 // is unnamed.
884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885 Decomp.getLSquareLoc());
886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887 ForVisibleRedeclaration);
888
889 // Build the variable that holds the non-decomposed object.
890 bool AddToScope = true;
891 NamedDecl *New =
892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893 MultiTemplateParamsArg(), AddToScope, Bindings);
894 if (AddToScope) {
895 S->AddDecl(New);
896 CurContext->addHiddenDecl(New);
897 }
898
899 if (isInOpenMPDeclareTargetContext())
900 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901
902 return New;
903}
904
907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909 if ((int64_t)Bindings.size() != NumElems) {
910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911 << DecompType << (unsigned)Bindings.size()
912 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913 << toString(NumElems, 10) << (NumElems < Bindings.size());
914 return true;
915 }
916
917 unsigned I = 0;
918 for (auto *B : Bindings) {
919 SourceLocation Loc = B->getLocation();
920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921 if (E.isInvalid())
922 return true;
923 E = GetInit(Loc, E.get(), I++);
924 if (E.isInvalid())
925 return true;
926 B->setBinding(ElemType, E.get());
927 }
928
929 return false;
930}
931
934 ValueDecl *Src, QualType DecompType,
935 const llvm::APSInt &NumElems,
936 QualType ElemType) {
938 S, Bindings, Src, DecompType, NumElems, ElemType,
939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940 ExprResult E = S.ActOnIntegerConstant(Loc, I);
941 if (E.isInvalid())
942 return ExprError();
943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944 });
945}
946
948 ValueDecl *Src, QualType DecompType,
949 const ConstantArrayType *CAT) {
950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951 llvm::APSInt(CAT->getSize()),
952 CAT->getElementType());
953}
954
956 ValueDecl *Src, QualType DecompType,
957 const VectorType *VT) {
959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
961 DecompType.getQualifiers()));
962}
963
966 ValueDecl *Src, QualType DecompType,
967 const ComplexType *CT) {
969 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
971 DecompType.getQualifiers()),
972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974 });
975}
976
979 const TemplateParameterList *Params) {
981 llvm::raw_svector_ostream OS(SS);
982 bool First = true;
983 unsigned I = 0;
984 for (auto &Arg : Args.arguments()) {
985 if (!First)
986 OS << ", ";
987 Arg.getArgument().print(PrintingPolicy, OS,
988 TemplateParameterList::shouldIncludeTypeForArgument(
989 PrintingPolicy, Params, I));
990 First = false;
991 I++;
992 }
993 return std::string(OS.str());
994}
995
996static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997 SourceLocation Loc, StringRef Trait,
999 unsigned DiagID) {
1000 auto DiagnoseMissing = [&] {
1001 if (DiagID)
1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003 Args, /*Params*/ nullptr);
1004 return true;
1005 };
1006
1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1009 if (!Std)
1010 return DiagnoseMissing();
1011
1012 // Look up the trait itself, within namespace std. We can diagnose various
1013 // problems with this lookup even if we've been asked to not diagnose a
1014 // missing specialization, because this can only fail if the user has been
1015 // declaring their own names in namespace std or we don't support the
1016 // standard library implementation in use.
1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1019 if (!S.LookupQualifiedName(Result, Std))
1020 return DiagnoseMissing();
1021 if (Result.isAmbiguous())
1022 return true;
1023
1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025 if (!TraitTD) {
1026 Result.suppressDiagnostics();
1027 NamedDecl *Found = *Result.begin();
1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029 S.Diag(Found->getLocation(), diag::note_declared_at);
1030 return true;
1031 }
1032
1033 // Build the template-id.
1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035 if (TraitTy.isNull())
1036 return true;
1037 if (!S.isCompleteType(Loc, TraitTy)) {
1038 if (DiagID)
1040 Loc, TraitTy, DiagID,
1042 TraitTD->getTemplateParameters()));
1043 return true;
1044 }
1045
1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047 assert(RD && "specialization of class template is not a class?");
1048
1049 // Look up the member of the trait type.
1050 S.LookupQualifiedName(TraitMemberLookup, RD);
1051 return TraitMemberLookup.isAmbiguous();
1052}
1053
1060
1065
1066namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067
1068static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069 llvm::APSInt &Size) {
1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072
1075
1076 // Form template argument list for tuple_size<T>.
1077 TemplateArgumentListInfo Args(Loc, Loc);
1079
1080 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081 // it's not tuple-like.
1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083 R.empty())
1084 return IsTupleLike::NotTupleLike;
1085
1086 // If we get this far, we've committed to the tuple interpretation, but
1087 // we can still fail if there actually isn't a usable ::value.
1088
1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090 LookupResult &R;
1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093 : R(R), Args(Args) {}
1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095 SourceLocation Loc) override {
1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1098 /*Params*/ nullptr);
1099 }
1100 } Diagnoser(R, Args);
1101
1102 ExprResult E =
1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104 if (E.isInvalid())
1105 return IsTupleLike::Error;
1106
1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108 if (E.isInvalid())
1109 return IsTupleLike::Error;
1110
1111 return IsTupleLike::TupleLike;
1112}
1113
1114/// \return std::tuple_element<I, T>::type.
1116 unsigned I, QualType T) {
1117 // Form template argument list for tuple_element<I, T>.
1118 TemplateArgumentListInfo Args(Loc, Loc);
1119 Args.addArgument(
1122
1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1126 S, R, Loc, "tuple_element", Args,
1127 diag::err_decomp_decl_std_tuple_element_not_specialized))
1128 return QualType();
1129
1130 auto *TD = R.getAsSingle<TypeDecl>();
1131 if (!TD) {
1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1135 /*Params*/ nullptr);
1136 if (!R.empty())
1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138 return QualType();
1139 }
1140
1141 return S.Context.getTypeDeclType(TD);
1142}
1143
1144namespace {
1145struct InitializingBinding {
1146 Sema &S;
1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1151 Ctx.Entity = BD;
1153 }
1154 ~InitializingBinding() {
1156 }
1157};
1158}
1159
1162 VarDecl *Src, QualType DecompType,
1163 const llvm::APSInt &TupleSize) {
1164 if ((int64_t)Bindings.size() != TupleSize) {
1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166 << DecompType << (unsigned)Bindings.size()
1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169 return true;
1170 }
1171
1172 if (Bindings.empty())
1173 return false;
1174
1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176
1177 // [dcl.decomp]p3:
1178 // The unqualified-id get is looked up in the scope of E by class member
1179 // access lookup ...
1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181 bool UseMemberGet = false;
1182 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183 if (auto *RD = DecompType->getAsCXXRecordDecl())
1184 S.LookupQualifiedName(MemberGet, RD);
1185 if (MemberGet.isAmbiguous())
1186 return true;
1187 // ... and if that finds at least one declaration that is a function
1188 // template whose first template parameter is a non-type parameter ...
1189 for (NamedDecl *D : MemberGet) {
1190 if (FunctionTemplateDecl *FTD =
1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192 TemplateParameterList *TPL = FTD->getTemplateParameters();
1193 if (TPL->size() != 0 &&
1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195 // ... the initializer is e.get<i>().
1196 UseMemberGet = true;
1197 break;
1198 }
1199 }
1200 }
1201 }
1202
1203 unsigned I = 0;
1204 for (auto *B : Bindings) {
1205 InitializingBinding InitContext(S, B);
1206 SourceLocation Loc = B->getLocation();
1207
1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209 if (E.isInvalid())
1210 return true;
1211
1212 // e is an lvalue if the type of the entity is an lvalue reference and
1213 // an xvalue otherwise
1214 if (!Src->getType()->isLValueReferenceType())
1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216 E.get(), nullptr, VK_XValue,
1218
1219 TemplateArgumentListInfo Args(Loc, Loc);
1220 Args.addArgument(
1222
1223 if (UseMemberGet) {
1224 // if [lookup of member get] finds at least one declaration, the
1225 // initializer is e.get<i-1>().
1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227 CXXScopeSpec(), SourceLocation(), nullptr,
1228 MemberGet, &Args, nullptr);
1229 if (E.isInvalid())
1230 return true;
1231
1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233 } else {
1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1235 // in the associated namespaces.
1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1240
1241 Expr *Arg = E.get();
1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243 }
1244 if (E.isInvalid())
1245 return true;
1246 Expr *Init = E.get();
1247
1248 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250 if (T.isNull())
1251 return true;
1252
1253 // each vi is a variable of type "reference to T" initialized with the
1254 // initializer, where the reference is an lvalue reference if the
1255 // initializer is an lvalue and an rvalue reference otherwise
1256 QualType RefType =
1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258 if (RefType.isNull())
1259 return true;
1260 auto *RefVD = VarDecl::Create(
1261 S.Context, Src->getDeclContext(), Loc, Loc,
1262 B->getDeclName().getAsIdentifierInfo(), RefType,
1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265 RefVD->setTSCSpec(Src->getTSCSpec());
1266 RefVD->setImplicit();
1267 if (Src->isInlineSpecified())
1268 RefVD->setInlineSpecified();
1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270
1273 InitializationSequence Seq(S, Entity, Kind, Init);
1274 E = Seq.Perform(S, Entity, Kind, Init);
1275 if (E.isInvalid())
1276 return true;
1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278 if (E.isInvalid())
1279 return true;
1280 RefVD->setInit(E.get());
1282
1284 DeclarationNameInfo(B->getDeclName(), Loc),
1285 RefVD);
1286 if (E.isInvalid())
1287 return true;
1288
1289 B->setBinding(T, E.get());
1290 I++;
1291 }
1292
1293 return false;
1294}
1295
1296/// Find the base class to decompose in a built-in decomposition of a class type.
1297/// This base class search is, unfortunately, not quite like any other that we
1298/// perform anywhere else in C++.
1300 const CXXRecordDecl *RD,
1301 CXXCastPath &BasePath) {
1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303 CXXBasePath &Path) {
1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305 };
1306
1307 const CXXRecordDecl *ClassWithFields = nullptr;
1309 if (RD->hasDirectFields())
1310 // [dcl.decomp]p4:
1311 // Otherwise, all of E's non-static data members shall be public direct
1312 // members of E ...
1313 ClassWithFields = RD;
1314 else {
1315 // ... or of ...
1316 CXXBasePaths Paths;
1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319 // If no classes have fields, just decompose RD itself. (This will work
1320 // if and only if zero bindings were provided.)
1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322 }
1323
1324 CXXBasePath *BestPath = nullptr;
1325 for (auto &P : Paths) {
1326 if (!BestPath)
1327 BestPath = &P;
1328 else if (!S.Context.hasSameType(P.back().Base->getType(),
1329 BestPath->back().Base->getType())) {
1330 // ... the same ...
1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332 << false << RD << BestPath->back().Base->getType()
1333 << P.back().Base->getType();
1334 return DeclAccessPair();
1335 } else if (P.Access < BestPath->Access) {
1336 BestPath = &P;
1337 }
1338 }
1339
1340 // ... unambiguous ...
1341 QualType BaseType = BestPath->back().Base->getType();
1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345 return DeclAccessPair();
1346 }
1347
1348 // ... [accessible, implied by other rules] base class of E.
1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350 *BestPath, diag::err_decomp_decl_inaccessible_base);
1351 AS = BestPath->Access;
1352
1353 ClassWithFields = BaseType->getAsCXXRecordDecl();
1354 S.BuildBasePathArray(Paths, BasePath);
1355 }
1356
1357 // The above search did not check whether the selected class itself has base
1358 // classes with fields, so check that now.
1359 CXXBasePaths Paths;
1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362 << (ClassWithFields == RD) << RD << ClassWithFields
1363 << Paths.front().back().Base->getType();
1364 return DeclAccessPair();
1365 }
1366
1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368}
1369
1371 ValueDecl *Src, QualType DecompType,
1372 const CXXRecordDecl *OrigRD) {
1373 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374 diag::err_incomplete_type))
1375 return true;
1376
1377 CXXCastPath BasePath;
1378 DeclAccessPair BasePair =
1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381 if (!RD)
1382 return true;
1384 DecompType.getQualifiers());
1385
1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387 unsigned NumFields = llvm::count_if(
1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389 assert(Bindings.size() != NumFields);
1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392 << (NumFields < Bindings.size());
1393 return true;
1394 };
1395
1396 // all of E's non-static data members shall be [...] well-formed
1397 // when named as e.name in the context of the structured binding,
1398 // E shall not have an anonymous union member, ...
1399 unsigned I = 0;
1400 for (auto *FD : RD->fields()) {
1401 if (FD->isUnnamedBitfield())
1402 continue;
1403
1404 // All the non-static data members are required to be nameable, so they
1405 // must all have names.
1406 if (!FD->getDeclName()) {
1407 if (RD->isLambda()) {
1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410 return true;
1411 }
1412
1413 if (FD->isAnonymousStructOrUnion()) {
1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415 << DecompType << FD->getType()->isUnionType();
1416 S.Diag(FD->getLocation(), diag::note_declared_at);
1417 return true;
1418 }
1419
1420 // FIXME: Are there any other ways we could have an anonymous member?
1421 }
1422
1423 // We have a real field to bind.
1424 if (I >= Bindings.size())
1425 return DiagnoseBadNumberOfBindings();
1426 auto *B = Bindings[I++];
1427 SourceLocation Loc = B->getLocation();
1428
1429 // The field must be accessible in the context of the structured binding.
1430 // We already checked that the base class is accessible.
1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432 // const_cast here.
1434 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1436 BasePair.getAccess(), FD->getAccess())));
1437
1438 // Initialize the binding to Src.FD.
1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440 if (E.isInvalid())
1441 return true;
1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443 VK_LValue, &BasePath);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447 CXXScopeSpec(), FD,
1448 DeclAccessPair::make(FD, FD->getAccess()),
1449 DeclarationNameInfo(FD->getDeclName(), Loc));
1450 if (E.isInvalid())
1451 return true;
1452
1453 // If the type of the member is T, the referenced type is cv T, where cv is
1454 // the cv-qualification of the decomposition expression.
1455 //
1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457 // 'const' to the type of the field.
1458 Qualifiers Q = DecompType.getQualifiers();
1459 if (FD->isMutable())
1460 Q.removeConst();
1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462 }
1463
1464 if (I != Bindings.size())
1465 return DiagnoseBadNumberOfBindings();
1466
1467 return false;
1468}
1469
1471 QualType DecompType = DD->getType();
1472
1473 // If the type of the decomposition is dependent, then so is the type of
1474 // each binding.
1475 if (DecompType->isDependentType()) {
1476 for (auto *B : DD->bindings())
1477 B->setType(Context.DependentTy);
1478 return;
1479 }
1480
1481 DecompType = DecompType.getNonReferenceType();
1483
1484 // C++1z [dcl.decomp]/2:
1485 // If E is an array type [...]
1486 // As an extension, we also support decomposition of built-in complex and
1487 // vector types.
1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490 DD->setInvalidDecl();
1491 return;
1492 }
1493 if (auto *VT = DecompType->getAs<VectorType>()) {
1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495 DD->setInvalidDecl();
1496 return;
1497 }
1498 if (auto *CT = DecompType->getAs<ComplexType>()) {
1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500 DD->setInvalidDecl();
1501 return;
1502 }
1503
1504 // C++1z [dcl.decomp]/3:
1505 // if the expression std::tuple_size<E>::value is a well-formed integral
1506 // constant expression, [...]
1507 llvm::APSInt TupleSize(32);
1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509 case IsTupleLike::Error:
1510 DD->setInvalidDecl();
1511 return;
1512
1513 case IsTupleLike::TupleLike:
1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515 DD->setInvalidDecl();
1516 return;
1517
1518 case IsTupleLike::NotTupleLike:
1519 break;
1520 }
1521
1522 // C++1z [dcl.dcl]/8:
1523 // [E shall be of array or non-union class type]
1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525 if (!RD || RD->isUnion()) {
1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527 << DD << !RD << DecompType;
1528 DD->setInvalidDecl();
1529 return;
1530 }
1531
1532 // C++1z [dcl.decomp]/4:
1533 // all of E's non-static data members shall be [...] direct members of
1534 // E or of the same unambiguous public base class of E, ...
1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536 DD->setInvalidDecl();
1537}
1538
1539/// Merge the exception specifications of two variable declarations.
1540///
1541/// This is called when there's a redeclaration of a VarDecl. The function
1542/// checks if the redeclaration might have an exception specification and
1543/// validates compatibility and merges the specs if necessary.
1545 // Shortcut if exceptions are disabled.
1546 if (!getLangOpts().CXXExceptions)
1547 return;
1548
1549 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550 "Should only be called if types are otherwise the same.");
1551
1552 QualType NewType = New->getType();
1553 QualType OldType = Old->getType();
1554
1555 // We're only interested in pointers and references to functions, as well
1556 // as pointers to member functions.
1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558 NewType = R->getPointeeType();
1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561 NewType = P->getPointeeType();
1562 OldType = OldType->castAs<PointerType>()->getPointeeType();
1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564 NewType = M->getPointeeType();
1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566 }
1567
1568 if (!NewType->isFunctionProtoType())
1569 return;
1570
1571 // There's lots of special cases for functions. For function pointers, system
1572 // libraries are hopefully not as broken so that we don't need these
1573 // workarounds.
1574 if (CheckEquivalentExceptionSpec(
1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577 New->setInvalidDecl();
1578 }
1579}
1580
1581/// CheckCXXDefaultArguments - Verify that the default arguments for a
1582/// function declaration are well-formed according to C++
1583/// [dcl.fct.default].
1585 unsigned NumParams = FD->getNumParams();
1586 unsigned ParamIdx = 0;
1587
1588 // This checking doesn't make sense for explicit specializations; their
1589 // default arguments are determined by the declaration we're specializing,
1590 // not by FD.
1592 return;
1593 if (auto *FTD = FD->getDescribedFunctionTemplate())
1594 if (FTD->isMemberSpecialization())
1595 return;
1596
1597 // Find first parameter with a default argument
1598 for (; ParamIdx < NumParams; ++ParamIdx) {
1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600 if (Param->hasDefaultArg())
1601 break;
1602 }
1603
1604 // C++20 [dcl.fct.default]p4:
1605 // In a given function declaration, each parameter subsequent to a parameter
1606 // with a default argument shall have a default argument supplied in this or
1607 // a previous declaration, unless the parameter was expanded from a
1608 // parameter pack, or shall be a function parameter pack.
1609 for (; ParamIdx < NumParams; ++ParamIdx) {
1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612 !(CurrentInstantiationScope &&
1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614 if (Param->isInvalidDecl())
1615 /* We already complained about this parameter. */;
1616 else if (Param->getIdentifier())
1617 Diag(Param->getLocation(),
1618 diag::err_param_default_argument_missing_name)
1619 << Param->getIdentifier();
1620 else
1621 Diag(Param->getLocation(),
1622 diag::err_param_default_argument_missing);
1623 }
1624 }
1625}
1626
1627/// Check that the given type is a literal type. Issue a diagnostic if not,
1628/// if Kind is Diagnose.
1629/// \return \c true if a problem has been found (and optionally diagnosed).
1630template <typename... Ts>
1632 SourceLocation Loc, QualType T, unsigned DiagID,
1633 Ts &&...DiagArgs) {
1634 if (T->isDependentType())
1635 return false;
1636
1637 switch (Kind) {
1638 case Sema::CheckConstexprKind::Diagnose:
1639 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640 std::forward<Ts>(DiagArgs)...);
1641
1642 case Sema::CheckConstexprKind::CheckValid:
1643 return !T->isLiteralType(SemaRef.Context);
1644 }
1645
1646 llvm_unreachable("unknown CheckConstexprKind");
1647}
1648
1649/// Determine whether a destructor cannot be constexpr due to
1651 const CXXDestructorDecl *DD,
1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654 const CXXRecordDecl *RD =
1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656 if (!RD || RD->hasConstexprDestructor())
1657 return true;
1658
1659 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661 << static_cast<int>(DD->getConstexprKind()) << !FD
1662 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665 }
1666 return false;
1667 };
1668
1669 const CXXRecordDecl *RD = DD->getParent();
1670 for (const CXXBaseSpecifier &B : RD->bases())
1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672 return false;
1673 for (const FieldDecl *FD : RD->fields())
1674 if (!Check(FD->getLocation(), FD->getType(), FD))
1675 return false;
1676 return true;
1677}
1678
1679/// Check whether a function's parameter types are all literal types. If so,
1680/// return true. If not, produce a suitable diagnostic and return false.
1682 const FunctionDecl *FD,
1684 unsigned ArgIndex = 0;
1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687 e = FT->param_type_end();
1688 i != e; ++i, ++ArgIndex) {
1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690 SourceLocation ParamLoc = PD->getLocation();
1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694 FD->isConsteval()))
1695 return false;
1696 }
1697 return true;
1698}
1699
1700/// Check whether a function's return type is a literal type. If so, return
1701/// true. If not, produce a suitable diagnostic and return false.
1702static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705 diag::err_constexpr_non_literal_return,
1706 FD->isConsteval()))
1707 return false;
1708 return true;
1709}
1710
1711/// Get diagnostic %select index for tag kind for
1712/// record diagnostic message.
1713/// WARNING: Indexes apply to particular diagnostics only!
1714///
1715/// \returns diagnostic %select index.
1717 switch (Tag) {
1718 case TTK_Struct: return 0;
1719 case TTK_Interface: return 1;
1720 case TTK_Class: return 2;
1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722 }
1723}
1724
1725static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726 Stmt *Body,
1728
1729// Check whether a function declaration satisfies the requirements of a
1730// constexpr function definition or a constexpr constructor definition. If so,
1731// return true. If not, produce appropriate diagnostics (unless asked not to by
1732// Kind) and return false.
1733//
1734// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1736 CheckConstexprKind Kind) {
1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738 if (MD && MD->isInstance()) {
1739 // C++11 [dcl.constexpr]p4:
1740 // The definition of a constexpr constructor shall satisfy the following
1741 // constraints:
1742 // - the class shall not have any virtual base classes;
1743 //
1744 // FIXME: This only applies to constructors and destructors, not arbitrary
1745 // member functions.
1746 const CXXRecordDecl *RD = MD->getParent();
1747 if (RD->getNumVBases()) {
1748 if (Kind == CheckConstexprKind::CheckValid)
1749 return false;
1750
1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752 << isa<CXXConstructorDecl>(NewFD)
1754 for (const auto &I : RD->vbases())
1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756 << I.getSourceRange();
1757 return false;
1758 }
1759 }
1760
1761 if (!isa<CXXConstructorDecl>(NewFD)) {
1762 // C++11 [dcl.constexpr]p3:
1763 // The definition of a constexpr function shall satisfy the following
1764 // constraints:
1765 // - it shall not be virtual; (removed in C++20)
1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767 if (Method && Method->isVirtual()) {
1768 if (getLangOpts().CPlusPlus20) {
1769 if (Kind == CheckConstexprKind::Diagnose)
1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771 } else {
1772 if (Kind == CheckConstexprKind::CheckValid)
1773 return false;
1774
1775 Method = Method->getCanonicalDecl();
1776 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777
1778 // If it's not obvious why this function is virtual, find an overridden
1779 // function which uses the 'virtual' keyword.
1780 const CXXMethodDecl *WrittenVirtual = Method;
1781 while (!WrittenVirtual->isVirtualAsWritten())
1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783 if (WrittenVirtual != Method)
1784 Diag(WrittenVirtual->getLocation(),
1785 diag::note_overridden_virtual_function);
1786 return false;
1787 }
1788 }
1789
1790 // - its return type shall be a literal type;
1791 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792 return false;
1793 }
1794
1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796 // A destructor can be constexpr only if the defaulted destructor could be;
1797 // we don't need to check the members and bases if we already know they all
1798 // have constexpr destructors.
1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800 if (Kind == CheckConstexprKind::CheckValid)
1801 return false;
1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803 return false;
1804 }
1805 }
1806
1807 // - each of its parameter types shall be a literal type;
1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809 return false;
1810
1811 Stmt *Body = NewFD->getBody();
1812 assert(Body &&
1813 "CheckConstexprFunctionDefinition called on function with no body");
1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815}
1816
1817/// Check the given declaration statement is legal within a constexpr function
1818/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819///
1820/// \return true if the body is OK (maybe only as an extension), false if we
1821/// have diagnosed a problem.
1822static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1825 // C++11 [dcl.constexpr]p3 and p4:
1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827 // contain only
1828 for (const auto *DclIt : DS->decls()) {
1829 switch (DclIt->getKind()) {
1830 case Decl::StaticAssert:
1831 case Decl::Using:
1832 case Decl::UsingShadow:
1833 case Decl::UsingDirective:
1834 case Decl::UnresolvedUsingTypename:
1835 case Decl::UnresolvedUsingValue:
1836 case Decl::UsingEnum:
1837 // - static_assert-declarations
1838 // - using-declarations,
1839 // - using-directives,
1840 // - using-enum-declaration
1841 continue;
1842
1843 case Decl::Typedef:
1844 case Decl::TypeAlias: {
1845 // - typedef declarations and alias-declarations that do not define
1846 // classes or enumerations,
1847 const auto *TN = cast<TypedefNameDecl>(DclIt);
1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849 // Don't allow variably-modified types in constexpr functions.
1850 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853 << TL.getSourceRange() << TL.getType()
1855 }
1856 return false;
1857 }
1858 continue;
1859 }
1860
1861 case Decl::Enum:
1862 case Decl::CXXRecord:
1863 // C++1y allows types to be defined, not just declared.
1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866 SemaRef.Diag(DS->getBeginLoc(),
1867 SemaRef.getLangOpts().CPlusPlus14
1868 ? diag::warn_cxx11_compat_constexpr_type_definition
1869 : diag::ext_constexpr_type_definition)
1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872 return false;
1873 }
1874 }
1875 continue;
1876
1877 case Decl::EnumConstant:
1878 case Decl::IndirectField:
1879 case Decl::ParmVar:
1880 // These can only appear with other declarations which are banned in
1881 // C++11 and permitted in C++1y, so ignore them.
1882 continue;
1883
1884 case Decl::Var:
1885 case Decl::Decomposition: {
1886 // C++1y [dcl.constexpr]p3 allows anything except:
1887 // a definition of a variable of non-literal type or of static or
1888 // thread storage duration or [before C++2a] for which no
1889 // initialization is performed.
1890 const auto *VD = cast<VarDecl>(DclIt);
1891 if (VD->isThisDeclarationADefinition()) {
1892 if (VD->isStaticLocal()) {
1893 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894 SemaRef.Diag(VD->getLocation(),
1895 SemaRef.getLangOpts().CPlusPlus2b
1896 ? diag::warn_cxx20_compat_constexpr_var
1897 : diag::ext_constexpr_static_var)
1899 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1900 } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1901 return false;
1902 }
1903 }
1904 if (SemaRef.LangOpts.CPlusPlus2b) {
1905 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1906 diag::warn_cxx20_compat_constexpr_var,
1907 isa<CXXConstructorDecl>(Dcl),
1908 /*variable of non-literal type*/ 2);
1909 } else if (CheckLiteralType(
1910 SemaRef, Kind, VD->getLocation(), VD->getType(),
1911 diag::err_constexpr_local_var_non_literal_type,
1912 isa<CXXConstructorDecl>(Dcl))) {
1913 return false;
1914 }
1915 if (!VD->getType()->isDependentType() &&
1916 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1917 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1918 SemaRef.Diag(
1919 VD->getLocation(),
1920 SemaRef.getLangOpts().CPlusPlus20
1921 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1922 : diag::ext_constexpr_local_var_no_init)
1924 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1925 return false;
1926 }
1927 continue;
1928 }
1929 }
1930 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1931 SemaRef.Diag(VD->getLocation(),
1932 SemaRef.getLangOpts().CPlusPlus14
1933 ? diag::warn_cxx11_compat_constexpr_local_var
1934 : diag::ext_constexpr_local_var)
1936 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1937 return false;
1938 }
1939 continue;
1940 }
1941
1942 case Decl::NamespaceAlias:
1943 case Decl::Function:
1944 // These are disallowed in C++11 and permitted in C++1y. Allow them
1945 // everywhere as an extension.
1946 if (!Cxx1yLoc.isValid())
1947 Cxx1yLoc = DS->getBeginLoc();
1948 continue;
1949
1950 default:
1951 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1953 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1954 }
1955 return false;
1956 }
1957 }
1958
1959 return true;
1960}
1961
1962/// Check that the given field is initialized within a constexpr constructor.
1963///
1964/// \param Dcl The constexpr constructor being checked.
1965/// \param Field The field being checked. This may be a member of an anonymous
1966/// struct or union nested within the class being checked.
1967/// \param Inits All declarations, including anonymous struct/union members and
1968/// indirect members, for which any initialization was provided.
1969/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1970/// multiple notes for different members to the same error.
1971/// \param Kind Whether we're diagnosing a constructor as written or determining
1972/// whether the formal requirements are satisfied.
1973/// \return \c false if we're checking for validity and the constructor does
1974/// not satisfy the requirements on a constexpr constructor.
1976 const FunctionDecl *Dcl,
1977 FieldDecl *Field,
1978 llvm::SmallSet<Decl*, 16> &Inits,
1979 bool &Diagnosed,
1981 // In C++20 onwards, there's nothing to check for validity.
1982 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1983 SemaRef.getLangOpts().CPlusPlus20)
1984 return true;
1985
1986 if (Field->isInvalidDecl())
1987 return true;
1988
1989 if (Field->isUnnamedBitfield())
1990 return true;
1991
1992 // Anonymous unions with no variant members and empty anonymous structs do not
1993 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1994 // indirect fields don't need initializing.
1995 if (Field->isAnonymousStructOrUnion() &&
1996 (Field->getType()->isUnionType()
1997 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1998 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1999 return true;
2000
2001 if (!Inits.count(Field)) {
2002 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2003 if (!Diagnosed) {
2004 SemaRef.Diag(Dcl->getLocation(),
2005 SemaRef.getLangOpts().CPlusPlus20
2006 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2007 : diag::ext_constexpr_ctor_missing_init);
2008 Diagnosed = true;
2009 }
2010 SemaRef.Diag(Field->getLocation(),
2011 diag::note_constexpr_ctor_missing_init);
2012 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2013 return false;
2014 }
2015 } else if (Field->isAnonymousStructOrUnion()) {
2016 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2017 for (auto *I : RD->fields())
2018 // If an anonymous union contains an anonymous struct of which any member
2019 // is initialized, all members must be initialized.
2020 if (!RD->isUnion() || Inits.count(I))
2021 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2022 Kind))
2023 return false;
2024 }
2025 return true;
2026}
2027
2028/// Check the provided statement is allowed in a constexpr function
2029/// definition.
2030static bool
2033 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2034 SourceLocation &Cxx2bLoc,
2036 // - its function-body shall be [...] a compound-statement that contains only
2037 switch (S->getStmtClass()) {
2038 case Stmt::NullStmtClass:
2039 // - null statements,
2040 return true;
2041
2042 case Stmt::DeclStmtClass:
2043 // - static_assert-declarations
2044 // - using-declarations,
2045 // - using-directives,
2046 // - typedef declarations and alias-declarations that do not define
2047 // classes or enumerations,
2048 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2049 return false;
2050 return true;
2051
2052 case Stmt::ReturnStmtClass:
2053 // - and exactly one return statement;
2054 if (isa<CXXConstructorDecl>(Dcl)) {
2055 // C++1y allows return statements in constexpr constructors.
2056 if (!Cxx1yLoc.isValid())
2057 Cxx1yLoc = S->getBeginLoc();
2058 return true;
2059 }
2060
2061 ReturnStmts.push_back(S->getBeginLoc());
2062 return true;
2063
2064 case Stmt::AttributedStmtClass:
2065 // Attributes on a statement don't affect its formal kind and hence don't
2066 // affect its validity in a constexpr function.
2068 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2069 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2070
2071 case Stmt::CompoundStmtClass: {
2072 // C++1y allows compound-statements.
2073 if (!Cxx1yLoc.isValid())
2074 Cxx1yLoc = S->getBeginLoc();
2075
2076 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2077 for (auto *BodyIt : CompStmt->body()) {
2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2079 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2080 return false;
2081 }
2082 return true;
2083 }
2084
2085 case Stmt::IfStmtClass: {
2086 // C++1y allows if-statements.
2087 if (!Cxx1yLoc.isValid())
2088 Cxx1yLoc = S->getBeginLoc();
2089
2090 IfStmt *If = cast<IfStmt>(S);
2091 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2092 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2093 return false;
2094 if (If->getElse() &&
2095 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2096 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2097 return false;
2098 return true;
2099 }
2100
2101 case Stmt::WhileStmtClass:
2102 case Stmt::DoStmtClass:
2103 case Stmt::ForStmtClass:
2104 case Stmt::CXXForRangeStmtClass:
2105 case Stmt::ContinueStmtClass:
2106 // C++1y allows all of these. We don't allow them as extensions in C++11,
2107 // because they don't make sense without variable mutation.
2108 if (!SemaRef.getLangOpts().CPlusPlus14)
2109 break;
2110 if (!Cxx1yLoc.isValid())
2111 Cxx1yLoc = S->getBeginLoc();
2112 for (Stmt *SubStmt : S->children()) {
2113 if (SubStmt &&
2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2116 return false;
2117 }
2118 return true;
2119
2120 case Stmt::SwitchStmtClass:
2121 case Stmt::CaseStmtClass:
2122 case Stmt::DefaultStmtClass:
2123 case Stmt::BreakStmtClass:
2124 // C++1y allows switch-statements, and since they don't need variable
2125 // mutation, we can reasonably allow them in C++11 as an extension.
2126 if (!Cxx1yLoc.isValid())
2127 Cxx1yLoc = S->getBeginLoc();
2128 for (Stmt *SubStmt : S->children()) {
2129 if (SubStmt &&
2130 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2131 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2132 return false;
2133 }
2134 return true;
2135
2136 case Stmt::LabelStmtClass:
2137 case Stmt::GotoStmtClass:
2138 if (Cxx2bLoc.isInvalid())
2139 Cxx2bLoc = S->getBeginLoc();
2140 for (Stmt *SubStmt : S->children()) {
2141 if (SubStmt &&
2142 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2143 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2144 return false;
2145 }
2146 return true;
2147
2148 case Stmt::GCCAsmStmtClass:
2149 case Stmt::MSAsmStmtClass:
2150 // C++2a allows inline assembly statements.
2151 case Stmt::CXXTryStmtClass:
2152 if (Cxx2aLoc.isInvalid())
2153 Cxx2aLoc = S->getBeginLoc();
2154 for (Stmt *SubStmt : S->children()) {
2155 if (SubStmt &&
2156 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2157 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158 return false;
2159 }
2160 return true;
2161
2162 case Stmt::CXXCatchStmtClass:
2163 // Do not bother checking the language mode (already covered by the
2164 // try block check).
2166 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2167 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2168 return false;
2169 return true;
2170
2171 default:
2172 if (!isa<Expr>(S))
2173 break;
2174
2175 // C++1y allows expression-statements.
2176 if (!Cxx1yLoc.isValid())
2177 Cxx1yLoc = S->getBeginLoc();
2178 return true;
2179 }
2180
2181 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2182 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2183 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2184 }
2185 return false;
2186}
2187
2188/// Check the body for the given constexpr function declaration only contains
2189/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2190///
2191/// \return true if the body is OK, false if we have found or diagnosed a
2192/// problem.
2193static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2194 Stmt *Body,
2197
2198 if (isa<CXXTryStmt>(Body)) {
2199 // C++11 [dcl.constexpr]p3:
2200 // The definition of a constexpr function shall satisfy the following
2201 // constraints: [...]
2202 // - its function-body shall be = delete, = default, or a
2203 // compound-statement
2204 //
2205 // C++11 [dcl.constexpr]p4:
2206 // In the definition of a constexpr constructor, [...]
2207 // - its function-body shall not be a function-try-block;
2208 //
2209 // This restriction is lifted in C++2a, as long as inner statements also
2210 // apply the general constexpr rules.
2211 switch (Kind) {
2212 case Sema::CheckConstexprKind::CheckValid:
2213 if (!SemaRef.getLangOpts().CPlusPlus20)
2214 return false;
2215 break;
2216
2217 case Sema::CheckConstexprKind::Diagnose:
2218 SemaRef.Diag(Body->getBeginLoc(),
2219 !SemaRef.getLangOpts().CPlusPlus20
2220 ? diag::ext_constexpr_function_try_block_cxx20
2221 : diag::warn_cxx17_compat_constexpr_function_try_block)
2223 break;
2224 }
2225 }
2226
2227 // - its function-body shall be [...] a compound-statement that contains only
2228 // [... list of cases ...]
2229 //
2230 // Note that walking the children here is enough to properly check for
2231 // CompoundStmt and CXXTryStmt body.
2232 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2233 for (Stmt *SubStmt : Body->children()) {
2234 if (SubStmt &&
2235 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2236 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237 return false;
2238 }
2239
2240 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2241 // If this is only valid as an extension, report that we don't satisfy the
2242 // constraints of the current language.
2243 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2244 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2245 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2246 return false;
2247 } else if (Cxx2bLoc.isValid()) {
2248 SemaRef.Diag(Cxx2bLoc,
2249 SemaRef.getLangOpts().CPlusPlus2b
2250 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2251 : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2253 } else if (Cxx2aLoc.isValid()) {
2254 SemaRef.Diag(Cxx2aLoc,
2255 SemaRef.getLangOpts().CPlusPlus20
2256 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2257 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2259 } else if (Cxx1yLoc.isValid()) {
2260 SemaRef.Diag(Cxx1yLoc,
2261 SemaRef.getLangOpts().CPlusPlus14
2262 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2263 : diag::ext_constexpr_body_invalid_stmt)
2265 }
2266
2267 if (const CXXConstructorDecl *Constructor
2268 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2269 const CXXRecordDecl *RD = Constructor->getParent();
2270 // DR1359:
2271 // - every non-variant non-static data member and base class sub-object
2272 // shall be initialized;
2273 // DR1460:
2274 // - if the class is a union having variant members, exactly one of them
2275 // shall be initialized;
2276 if (RD->isUnion()) {
2277 if (Constructor->getNumCtorInitializers() == 0 &&
2278 RD->hasVariantMembers()) {
2279 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2280 SemaRef.Diag(
2281 Dcl->getLocation(),
2282 SemaRef.getLangOpts().CPlusPlus20
2283 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2284 : diag::ext_constexpr_union_ctor_no_init);
2285 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2286 return false;
2287 }
2288 }
2289 } else if (!Constructor->isDependentContext() &&
2290 !Constructor->isDelegatingConstructor()) {
2291 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2292
2293 // Skip detailed checking if we have enough initializers, and we would
2294 // allow at most one initializer per member.
2295 bool AnyAnonStructUnionMembers = false;
2296 unsigned Fields = 0;
2298 E = RD->field_end(); I != E; ++I, ++Fields) {
2299 if (I->isAnonymousStructOrUnion()) {
2300 AnyAnonStructUnionMembers = true;
2301 break;
2302 }
2303 }
2304 // DR1460:
2305 // - if the class is a union-like class, but is not a union, for each of
2306 // its anonymous union members having variant members, exactly one of
2307 // them shall be initialized;
2308 if (AnyAnonStructUnionMembers ||
2309 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2310 // Check initialization of non-static data members. Base classes are
2311 // always initialized so do not need to be checked. Dependent bases
2312 // might not have initializers in the member initializer list.
2313 llvm::SmallSet<Decl*, 16> Inits;
2314 for (const auto *I: Constructor->inits()) {
2315 if (FieldDecl *FD = I->getMember())
2316 Inits.insert(FD);
2317 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2318 Inits.insert(ID->chain_begin(), ID->chain_end());
2319 }
2320
2321 bool Diagnosed = false;
2322 for (auto *I : RD->fields())
2323 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2324 Kind))
2325 return false;
2326 }
2327 }
2328 } else {
2329 if (ReturnStmts.empty()) {
2330 // C++1y doesn't require constexpr functions to contain a 'return'
2331 // statement. We still do, unless the return type might be void, because
2332 // otherwise if there's no return statement, the function cannot
2333 // be used in a core constant expression.
2334 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2335 (Dcl->getReturnType()->isVoidType() ||
2336 Dcl->getReturnType()->isDependentType());
2337 switch (Kind) {
2338 case Sema::CheckConstexprKind::Diagnose:
2339 SemaRef.Diag(Dcl->getLocation(),
2340 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2341 : diag::err_constexpr_body_no_return)
2342 << Dcl->isConsteval();
2343 if (!OK)
2344 return false;
2345 break;
2346
2347 case Sema::CheckConstexprKind::CheckValid:
2348 // The formal requirements don't include this rule in C++14, even
2349 // though the "must be able to produce a constant expression" rules
2350 // still imply it in some cases.
2351 if (!SemaRef.getLangOpts().CPlusPlus14)
2352 return false;
2353 break;
2354 }
2355 } else if (ReturnStmts.size() > 1) {
2356 switch (Kind) {
2357 case Sema::CheckConstexprKind::Diagnose:
2358 SemaRef.Diag(
2359 ReturnStmts.back(),
2360 SemaRef.getLangOpts().CPlusPlus14
2361 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2362 : diag::ext_constexpr_body_multiple_return);
2363 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2364 SemaRef.Diag(ReturnStmts[I],
2365 diag::note_constexpr_body_previous_return);
2366 break;
2367
2368 case Sema::CheckConstexprKind::CheckValid:
2369 if (!SemaRef.getLangOpts().CPlusPlus14)
2370 return false;
2371 break;
2372 }
2373 }
2374 }
2375
2376 // C++11 [dcl.constexpr]p5:
2377 // if no function argument values exist such that the function invocation
2378 // substitution would produce a constant expression, the program is
2379 // ill-formed; no diagnostic required.
2380 // C++11 [dcl.constexpr]p3:
2381 // - every constructor call and implicit conversion used in initializing the
2382 // return value shall be one of those allowed in a constant expression.
2383 // C++11 [dcl.constexpr]p4:
2384 // - every constructor involved in initializing non-static data members and
2385 // base class sub-objects shall be a constexpr constructor.
2386 //
2387 // Note that this rule is distinct from the "requirements for a constexpr
2388 // function", so is not checked in CheckValid mode.
2390 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2391 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2392 SemaRef.Diag(Dcl->getLocation(),
2393 diag::ext_constexpr_function_never_constant_expr)
2394 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2395 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2396 SemaRef.Diag(Diags[I].first, Diags[I].second);
2397 // Don't return false here: we allow this for compatibility in
2398 // system headers.
2399 }
2400
2401 return true;
2402}
2403
2404/// Get the class that is directly named by the current context. This is the
2405/// class for which an unqualified-id in this scope could name a constructor
2406/// or destructor.
2407///
2408/// If the scope specifier denotes a class, this will be that class.
2409/// If the scope specifier is empty, this will be the class whose
2410/// member-specification we are currently within. Otherwise, there
2411/// is no such class.
2413 assert(getLangOpts().CPlusPlus && "No class names in C!");
2414
2415 if (SS && SS->isInvalid())
2416 return nullptr;
2417
2418 if (SS && SS->isNotEmpty()) {
2419 DeclContext *DC = computeDeclContext(*SS, true);
2420 return dyn_cast_or_null<CXXRecordDecl>(DC);
2421 }
2422
2423 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2424}
2425
2426/// isCurrentClassName - Determine whether the identifier II is the
2427/// name of the class type currently being defined. In the case of
2428/// nested classes, this will only return true if II is the name of
2429/// the innermost class.
2431 const CXXScopeSpec *SS) {
2432 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2433 return CurDecl && &II == CurDecl->getIdentifier();
2434}
2435
2436/// Determine whether the identifier II is a typo for the name of
2437/// the class type currently being defined. If so, update it to the identifier
2438/// that should have been used.
2440 assert(getLangOpts().CPlusPlus && "No class names in C!");
2441
2442 if (!getLangOpts().SpellChecking)
2443 return false;
2444
2445 CXXRecordDecl *CurDecl;
2446 if (SS && SS->isSet() && !SS->isInvalid()) {
2447 DeclContext *DC = computeDeclContext(*SS, true);
2448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2449 } else
2450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2451
2452 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2453 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2454 < II->getLength()) {
2455 II = CurDecl->getIdentifier();
2456 return true;
2457 }
2458
2459 return false;
2460}
2461
2462/// Determine whether the given class is a base class of the given
2463/// class, including looking at dependent bases.
2465 const CXXRecordDecl *Current) {
2467
2468 Class = Class->getCanonicalDecl();
2469 while (true) {
2470 for (const auto &I : Current->bases()) {
2471 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2472 if (!Base)
2473 continue;
2474
2475 Base = Base->getDefinition();
2476 if (!Base)
2477 continue;
2478
2479 if (Base->getCanonicalDecl() == Class)
2480 return true;
2481
2482 Queue.push_back(Base);
2483 }
2484
2485 if (Queue.empty())
2486 return false;
2487
2488 Current = Queue.pop_back_val();
2489 }
2490
2491 return false;
2492}
2493
2494/// Check the validity of a C++ base class specifier.
2495///
2496/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2497/// and returns NULL otherwise.
2500 SourceRange SpecifierRange,
2501 bool Virtual, AccessSpecifier Access,
2502 TypeSourceInfo *TInfo,
2503 SourceLocation EllipsisLoc) {
2504 // In HLSL, unspecified class access is public rather than private.
2505 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2506 Access == AS_none)
2507 Access = AS_public;
2508
2509 QualType BaseType = TInfo->getType();
2510 if (BaseType->containsErrors()) {
2511 // Already emitted a diagnostic when parsing the error type.
2512 return nullptr;
2513 }
2514 // C++ [class.union]p1:
2515 // A union shall not have base classes.
2516 if (Class->isUnion()) {
2517 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2518 << SpecifierRange;
2519 return nullptr;
2520 }
2521
2522 if (EllipsisLoc.isValid() &&
2524 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2525 << TInfo->getTypeLoc().getSourceRange();
2526 EllipsisLoc = SourceLocation();
2527 }
2528
2529 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2530
2531 if (BaseType->isDependentType()) {
2532 // Make sure that we don't have circular inheritance among our dependent
2533 // bases. For non-dependent bases, the check for completeness below handles
2534 // this.
2535 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2536 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2537 ((BaseDecl = BaseDecl->getDefinition()) &&
2538 findCircularInheritance(Class, BaseDecl))) {
2539 Diag(BaseLoc, diag::err_circular_inheritance)
2540 << BaseType << Context.getTypeDeclType(Class);
2541
2542 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2543 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2544 << BaseType;
2545
2546 return nullptr;
2547 }
2548 }
2549
2550 // Make sure that we don't make an ill-formed AST where the type of the
2551 // Class is non-dependent and its attached base class specifier is an
2552 // dependent type, which violates invariants in many clang code paths (e.g.
2553 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2554 // explicitly mark the Class decl invalid. The diagnostic was already
2555 // emitted.
2556 if (!Class->getTypeForDecl()->isDependentType())
2557 Class->setInvalidDecl();
2558 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2559 Class->getTagKind() == TTK_Class,
2560 Access, TInfo, EllipsisLoc);
2561 }
2562
2563 // Base specifiers must be record types.
2564 if (!BaseType->isRecordType()) {
2565 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2566 return nullptr;
2567 }
2568
2569 // C++ [class.union]p1:
2570 // A union shall not be used as a base class.
2571 if (BaseType->isUnionType()) {
2572 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2573 return nullptr;
2574 }
2575
2576 // For the MS ABI, propagate DLL attributes to base class templates.
2577 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2578 if (Attr *ClassAttr = getDLLAttr(Class)) {
2579 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2580 BaseType->getAsCXXRecordDecl())) {
2581 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2582 BaseLoc);
2583 }
2584 }
2585 }
2586
2587 // C++ [class.derived]p2:
2588 // The class-name in a base-specifier shall not be an incompletely
2589 // defined class.
2590 if (RequireCompleteType(BaseLoc, BaseType,
2591 diag::err_incomplete_base_class, SpecifierRange)) {
2592 Class->setInvalidDecl();
2593 return nullptr;
2594 }
2595
2596 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2597 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2598 assert(BaseDecl && "Record type has no declaration");
2599 BaseDecl = BaseDecl->getDefinition();
2600 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2601 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2602 assert(CXXBaseDecl && "Base type is not a C++ type");
2603
2604 // Microsoft docs say:
2605 // "If a base-class has a code_seg attribute, derived classes must have the
2606 // same attribute."
2607 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2608 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2609 if ((DerivedCSA || BaseCSA) &&
2610 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2611 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2612 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2613 << CXXBaseDecl;
2614 return nullptr;
2615 }
2616
2617 // A class which contains a flexible array member is not suitable for use as a
2618 // base class:
2619 // - If the layout determines that a base comes before another base,
2620 // the flexible array member would index into the subsequent base.
2621 // - If the layout determines that base comes before the derived class,
2622 // the flexible array member would index into the derived class.
2623 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2624 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2625 << CXXBaseDecl->getDeclName();
2626 return nullptr;
2627 }
2628
2629 // C++ [class]p3:
2630 // If a class is marked final and it appears as a base-type-specifier in
2631 // base-clause, the program is ill-formed.
2632 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2633 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2634 << CXXBaseDecl->getDeclName()
2635 << FA->isSpelledAsSealed();
2636 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2637 << CXXBaseDecl->getDeclName() << FA->getRange();
2638 return nullptr;
2639 }
2640
2641 if (BaseDecl->isInvalidDecl())
2642 Class->setInvalidDecl();
2643
2644 // Create the base specifier.
2645 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2646 Class->getTagKind() == TTK_Class,
2647 Access, TInfo, EllipsisLoc);
2648}
2649
2650/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2651/// one entry in the base class list of a class specifier, for
2652/// example:
2653/// class foo : public bar, virtual private baz {
2654/// 'public bar' and 'virtual private baz' are each base-specifiers.
2656 const ParsedAttributesView &Attributes,
2657 bool Virtual, AccessSpecifier Access,
2658 ParsedType basetype, SourceLocation BaseLoc,
2659 SourceLocation EllipsisLoc) {
2660 if (!classdecl)
2661 return true;
2662
2663 AdjustDeclIfTemplate(classdecl);
2664 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2665 if (!Class)
2666 return true;
2667
2668 // We haven't yet attached the base specifiers.
2669 Class->setIsParsingBaseSpecifiers();
2670
2671 // We do not support any C++11 attributes on base-specifiers yet.
2672 // Diagnose any attributes we see.
2673 for (const ParsedAttr &AL : Attributes) {
2674 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2675 continue;
2676 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2677 ? (unsigned)diag::warn_unknown_attribute_ignored
2678 : (unsigned)diag::err_base_specifier_attribute)
2679 << AL << AL.getRange();
2680 }
2681
2682 TypeSourceInfo *TInfo = nullptr;
2683 GetTypeFromParser(basetype, &TInfo);
2684
2685 if (EllipsisLoc.isInvalid() &&
2686 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2687 UPPC_BaseType))
2688 return true;
2689
2690 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2691 Virtual, Access, TInfo,
2692 EllipsisLoc))
2693 return BaseSpec;
2694 else
2695 Class->setInvalidDecl();
2696
2697 return true;
2698}
2699
2700/// Use small set to collect indirect bases. As this is only used
2701/// locally, there's no need to abstract the small size parameter.
2703
2704/// Recursively add the bases of Type. Don't add Type itself.
2705static void
2707 const QualType &Type)
2708{
2709 // Even though the incoming type is a base, it might not be
2710 // a class -- it could be a template parm, for instance.
2711 if (auto Rec = Type->getAs<RecordType>()) {
2712 auto Decl = Rec->getAsCXXRecordDecl();
2713
2714 // Iterate over its bases.
2715 for (const auto &BaseSpec : Decl->bases()) {
2716 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2718 if (Set.insert(Base).second)
2719 // If we've not already seen it, recurse.
2720 NoteIndirectBases(Context, Set, Base);
2721 }
2722 }
2723}
2724
2725/// Performs the actual work of attaching the given base class
2726/// specifiers to a C++ class.
2729 if (Bases.empty())
2730 return false;
2731
2732 // Used to keep track of which base types we have already seen, so
2733 // that we can properly diagnose redundant direct base types. Note
2734 // that the key is always the unqualified canonical type of the base
2735 // class.
2736 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2737
2738 // Used to track indirect bases so we can see if a direct base is
2739 // ambiguous.
2740 IndirectBaseSet IndirectBaseTypes;
2741
2742 // Copy non-redundant base specifiers into permanent storage.
2743 unsigned NumGoodBases = 0;
2744 bool Invalid = false;
2745 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2746 QualType NewBaseType
2747 = Context.getCanonicalType(Bases[idx]->getType());
2748 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2749
2750 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2751 if (KnownBase) {
2752 // C++ [class.mi]p3:
2753 // A class shall not be specified as a direct base class of a
2754 // derived class more than once.
2755 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2756 << KnownBase->getType() << Bases[idx]->getSourceRange();
2757
2758 // Delete the duplicate base class specifier; we're going to
2759 // overwrite its pointer later.
2760 Context.Deallocate(Bases[idx]);
2761
2762 Invalid = true;
2763 } else {
2764 // Okay, add this new base class.
2765 KnownBase = Bases[idx];
2766 Bases[NumGoodBases++] = Bases[idx];
2767
2768 if (NewBaseType->isDependentType())
2769 continue;
2770 // Note this base's direct & indirect bases, if there could be ambiguity.
2771 if (Bases.size() > 1)
2772 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2773
2774 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2775 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2776 if (Class->isInterface() &&
2777 (!RD->isInterfaceLike() ||
2778 KnownBase->getAccessSpecifier() != AS_public)) {
2779 // The Microsoft extension __interface does not permit bases that
2780 // are not themselves public interfaces.
2781 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2782 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2783 << RD->getSourceRange();
2784 Invalid = true;
2785 }
2786 if (RD->hasAttr<WeakAttr>())
2787 Class->addAttr(WeakAttr::CreateImplicit(Context));
2788 }
2789 }
2790 }
2791
2792 // Attach the remaining base class specifiers to the derived class.
2793 Class->setBases(Bases.data(), NumGoodBases);
2794
2795 // Check that the only base classes that are duplicate are virtual.
2796 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2797 // Check whether this direct base is inaccessible due to ambiguity.
2798 QualType BaseType = Bases[idx]->getType();
2799
2800 // Skip all dependent types in templates being used as base specifiers.
2801 // Checks below assume that the base specifier is a CXXRecord.
2802 if (BaseType->isDependentType())
2803 continue;
2804
2805 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2807
2808 if (IndirectBaseTypes.count(CanonicalBase)) {
2809 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2810 /*DetectVirtual=*/true);
2811 bool found
2812 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2813 assert(found);
2814 (void)found;
2815
2816 if (Paths.isAmbiguous(CanonicalBase))
2817 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2818 << BaseType << getAmbiguousPathsDisplayString(Paths)
2819 << Bases[idx]->getSourceRange();
2820 else
2821 assert(Bases[idx]->isVirtual());
2822 }
2823
2824 // Delete the base class specifier, since its data has been copied
2825 // into the CXXRecordDecl.
2826 Context.Deallocate(Bases[idx]);
2827 }
2828
2829 return Invalid;
2830}
2831
2832/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2833/// class, after checking whether there are any duplicate base
2834/// classes.
2837 if (!ClassDecl || Bases.empty())
2838 return;
2839
2840 AdjustDeclIfTemplate(ClassDecl);
2841 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2842}
2843
2844/// Determine whether the type \p Derived is a C++ class that is
2845/// derived from the type \p Base.
2847 if (!getLangOpts().CPlusPlus)
2848 return false;
2849
2850 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2851 if (!DerivedRD)
2852 return false;
2853
2854 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2855 if (!BaseRD)
2856 return false;
2857
2858 // If either the base or the derived type is invalid, don't try to
2859 // check whether one is derived from the other.
2860 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2861 return false;
2862
2863 // FIXME: In a modules build, do we need the entire path to be visible for us
2864 // to be able to use the inheritance relationship?
2865 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2866 return false;
2867
2868 return DerivedRD->isDerivedFrom(BaseRD);
2869}
2870
2871/// Determine whether the type \p Derived is a C++ class that is
2872/// derived from the type \p Base.
2874 CXXBasePaths &Paths) {
2875 if (!getLangOpts().CPlusPlus)
2876 return false;
2877
2878 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2879 if (!DerivedRD)
2880 return false;
2881
2882 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2883 if (!BaseRD)
2884 return false;
2885
2886 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2887 return false;
2888
2889 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2890}
2891
2892static void BuildBasePathArray(const CXXBasePath &Path,
2893 CXXCastPath &BasePathArray) {
2894 // We first go backward and check if we have a virtual base.
2895 // FIXME: It would be better if CXXBasePath had the base specifier for
2896 // the nearest virtual base.
2897 unsigned Start = 0;
2898 for (unsigned I = Path.size(); I != 0; --I) {
2899 if (Path[I - 1].Base->isVirtual()) {
2900 Start = I - 1;
2901 break;
2902 }
2903 }
2904
2905 // Now add all bases.
2906 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2907 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2908}
2909
2910
2912 CXXCastPath &BasePathArray) {
2913 assert(BasePathArray.empty() && "Base path array must be empty!");
2914 assert(Paths.isRecordingPaths() && "Must record paths!");
2915 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2916}
2917/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2918/// conversion (where Derived and Base are class types) is
2919/// well-formed, meaning that the conversion is unambiguous (and
2920/// that all of the base classes are accessible). Returns true
2921/// and emits a diagnostic if the code is ill-formed, returns false
2922/// otherwise. Loc is the location where this routine should point to
2923/// if there is an error, and Range is the source range to highlight
2924/// if there is an error.
2925///
2926/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2927/// diagnostic for the respective type of error will be suppressed, but the
2928/// check for ill-formed code will still be performed.
2929bool
2931 unsigned InaccessibleBaseID,
2932 unsigned AmbiguousBaseConvID,
2933 SourceLocation Loc, SourceRange Range,
2934 DeclarationName Name,
2935 CXXCastPath *BasePath,
2936 bool IgnoreAccess) {
2937 // First, determine whether the path from Derived to Base is
2938 // ambiguous. This is slightly more expensive than checking whether
2939 // the Derived to Base conversion exists, because here we need to
2940 // explore multiple paths to determine if there is an ambiguity.
2941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2942 /*DetectVirtual=*/false);
2943 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2944 if (!DerivationOkay)
2945 return true;
2946
2947 const CXXBasePath *Path = nullptr;
2948 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2949 Path = &Paths.front();
2950
2951 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2952 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2953 // user to access such bases.
2954 if (!Path && getLangOpts().MSVCCompat) {
2955 for (const CXXBasePath &PossiblePath : Paths) {
2956 if (PossiblePath.size() == 1) {
2957 Path = &PossiblePath;
2958 if (AmbiguousBaseConvID)
2959 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2960 << Base << Derived << Range;
2961 break;
2962 }
2963 }
2964 }
2965
2966 if (Path) {
2967 if (!IgnoreAccess) {
2968 // Check that the base class can be accessed.
2969 switch (
2970 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2971 case AR_inaccessible:
2972 return true;
2973 case AR_accessible:
2974 case AR_dependent:
2975 case AR_delayed:
2976 break;
2977 }
2978 }
2979
2980 // Build a base path if necessary.
2981 if (BasePath)
2982 ::BuildBasePathArray(*Path, *BasePath);
2983 return false;
2984 }
2985
2986 if (AmbiguousBaseConvID) {
2987 // We know that the derived-to-base conversion is ambiguous, and
2988 // we're going to produce a diagnostic. Perform the derived-to-base
2989 // search just one more time to compute all of the possible paths so
2990 // that we can print them out. This is more expensive than any of
2991 // the previous derived-to-base checks we've done, but at this point
2992 // performance isn't as much of an issue.
2993 Paths.clear();
2994 Paths.setRecordingPaths(true);
2995 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2996 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2997 (void)StillOkay;
2998
2999 // Build up a textual representation of the ambiguous paths, e.g.,
3000 // D -> B -> A, that will be used to illustrate the ambiguous
3001 // conversions in the diagnostic. We only print one of the paths
3002 // to each base class subobject.
3003 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3004
3005 Diag(Loc, AmbiguousBaseConvID)
3006 << Derived << Base << PathDisplayStr << Range << Name;
3007 }
3008 return true;
3009}
3010
3011bool
3013 SourceLocation Loc, SourceRange Range,
3014 CXXCastPath *BasePath,
3015 bool IgnoreAccess) {
3016 return CheckDerivedToBaseConversion(
3017 Derived, Base, diag::err_upcast_to_inaccessible_base,
3018 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3019 BasePath, IgnoreAccess);
3020}
3021
3022
3023/// Builds a string representing ambiguous paths from a
3024/// specific derived class to different subobjects of the same base
3025/// class.
3026///
3027/// This function builds a string that can be used in error messages
3028/// to show the different paths that one can take through the
3029/// inheritance hierarchy to go from the derived class to different
3030/// subobjects of a base class. The result looks something like this:
3031/// @code
3032/// struct D -> struct B -> struct A
3033/// struct D -> struct C -> struct A
3034/// @endcode
3036 std::string PathDisplayStr;
3037 std::set<unsigned> DisplayedPaths;
3038 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3039 Path != Paths.end(); ++Path) {
3040 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3041 // We haven't displayed a path to this particular base
3042 // class subobject yet.
3043 PathDisplayStr += "\n ";
3044 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3045 for (CXXBasePath::const_iterator Element = Path->begin();
3046 Element != Path->end(); ++Element)
3047 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3048 }
3049 }
3050
3051 return PathDisplayStr;
3052}
3053
3054//===----------------------------------------------------------------------===//
3055// C++ class member Handling
3056//===----------------------------------------------------------------------===//
3057
3058/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3060 SourceLocation ColonLoc,
3061 const ParsedAttributesView &Attrs) {
3062 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3063 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3064 ASLoc, ColonLoc);
3065 CurContext->addHiddenDecl(ASDecl);
3066 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3067}
3068
3069/// CheckOverrideControl - Check C++11 override control semantics.
3071 if (D->isInvalidDecl())
3072 return;
3073
3074 // We only care about "override" and "final" declarations.
3075 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3076 return;
3077
3078 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3079
3080 // We can't check dependent instance methods.
3081 if (MD && MD->isInstance() &&
3082 (MD->getParent()->hasAnyDependentBases() ||
3083 MD->getType()->isDependentType()))
3084 return;
3085
3086 if (MD && !MD->isVirtual()) {
3087 // If we have a non-virtual method, check if if hides a virtual method.
3088 // (In that case, it's most likely the method has the wrong type.)
3089 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3090 FindHiddenVirtualMethods(MD, OverloadedMethods);
3091
3092 if (!OverloadedMethods.empty()) {
3093 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3094 Diag(OA->getLocation(),
3095 diag::override_keyword_hides_virtual_member_function)
3096 << "override" << (OverloadedMethods.size() > 1);
3097 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3098 Diag(FA->getLocation(),
3099 diag::override_keyword_hides_virtual_member_function)
3100 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3101 << (OverloadedMethods.size() > 1);
3102 }
3103 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3104 MD->setInvalidDecl();
3105 return;
3106 }
3107 // Fall through into the general case diagnostic.
3108 // FIXME: We might want to attempt typo correction here.
3109 }
3110
3111 if (!MD || !MD->isVirtual()) {
3112 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3113 Diag(OA->getLocation(),
3114 diag::override_keyword_only_allowed_on_virtual_member_functions)
3115 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3116 D->dropAttr<OverrideAttr>();
3117 }
3118 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3119 Diag(FA->getLocation(),
3120 diag::override_keyword_only_allowed_on_virtual_member_functions)
3121 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3122 << FixItHint::CreateRemoval(FA->getLocation());
3123 D->dropAttr<FinalAttr>();
3124 }
3125 return;
3126 }
3127
3128 // C++11 [class.virtual]p5:
3129 // If a function is marked with the virt-specifier override and
3130 // does not override a member function of a base class, the program is
3131 // ill-formed.
3132 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3133 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3134 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3135 << MD->getDeclName();
3136}
3137
3139 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3140 return;
3141 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3142 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3143 return;
3144
3145 SourceLocation Loc = MD->getLocation();
3146 SourceLocation SpellingLoc = Loc;
3147 if (getSourceManager().isMacroArgExpansion(Loc))
3148 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3149 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3150 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3151 return;
3152
3153 if (MD->size_overridden_methods() > 0) {
3154 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3155 unsigned DiagID =
3156 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3157 ? DiagInconsistent
3158 : DiagSuggest;
3159 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3160 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3161 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3162 };
3163 if (isa<CXXDestructorDecl>(MD))
3164 EmitDiag(
3165 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3166 diag::warn_suggest_destructor_marked_not_override_overriding);
3167 else
3168 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3169 diag::warn_suggest_function_marked_not_override_overriding);
3170 }
3171}
3172
3173/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3174/// function overrides a virtual member function marked 'final', according to
3175/// C++11 [class.virtual]p4.
3177 const CXXMethodDecl *Old) {
3178 FinalAttr *FA = Old->getAttr<FinalAttr>();
3179 if (!FA)
3180 return false;
3181
3182 Diag(New->getLocation(), diag::err_final_function_overridden)
3183 << New->getDeclName()
3184 << FA->isSpelledAsSealed();
3185 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3186 return true;
3187}
3188
3190 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3191 // FIXME: Destruction of ObjC lifetime types has side-effects.
3192 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3193 return !RD->isCompleteDefinition() ||
3194 !RD->hasTrivialDefaultConstructor() ||
3195 !RD->hasTrivialDestructor();
3196 return false;
3197}
3198
3201 llvm::find_if(list, [](const ParsedAttr &AL) {
3202 return AL.isDeclspecPropertyAttribute();
3203 });
3204 if (Itr != list.end())
3205 return &*Itr;
3206 return nullptr;
3207}
3208
3209// Check if there is a field shadowing.
3210void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3211 DeclarationName FieldName,
3212 const CXXRecordDecl *RD,
3213 bool DeclIsField) {
3214 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3215 return;
3216
3217 // To record a shadowed field in a base
3218 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3219 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3220 CXXBasePath &Path) {
3221 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3222 // Record an ambiguous path directly
3223 if (Bases.find(Base) != Bases.end())
3224 return true;
3225 for (const auto Field : Base->lookup(FieldName)) {
3226 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3227 Field->getAccess() != AS_private) {
3228 assert(Field->getAccess() != AS_none);
3229 assert(Bases.find(Base) == Bases.end());
3230 Bases[Base] = Field;
3231 return true;
3232 }
3233 }
3234 return false;
3235 };
3236
3237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3238 /*DetectVirtual=*/true);
3239 if (!RD->lookupInBases(FieldShadowed, Paths))
3240 return;
3241
3242 for (const auto &P : Paths) {
3243 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3244 auto It = Bases.find(Base);
3245 // Skip duplicated bases
3246 if (It == Bases.end())
3247 continue;
3248 auto BaseField = It->second;
3249 assert(BaseField->getAccess() != AS_private);
3250 if (AS_none !=
3251 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3252 Diag(Loc, diag::warn_shadow_field)
3253 << FieldName << RD << Base << DeclIsField;
3254 Diag(BaseField->getLocation(), diag::note_shadow_field);
3255 Bases.erase(It);
3256 }
3257 }
3258}
3259
3260/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3261/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3262/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3263/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3264/// present (but parsing it has been deferred).
3265NamedDecl *
3267 MultiTemplateParamsArg TemplateParameterLists,
3268 Expr *BW, const VirtSpecifiers &VS,
3269 InClassInitStyle InitStyle) {
3270 const DeclSpec &DS = D.getDeclSpec();
3271 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3272 DeclarationName Name = NameInfo.getName();
3273 SourceLocation Loc = NameInfo.getLoc();
3274
3275 // For anonymous bitfields, the location should point to the type.
3276 if (Loc.isInvalid())
3277 Loc = D.getBeginLoc();
3278
3279 Expr *BitWidth = static_cast<Expr*>(BW);
3280
3281 assert(isa<CXXRecordDecl>(CurContext));
3282 assert(!DS.isFriendSpecified());
3283
3284 bool isFunc = D.isDeclarationOfFunction();
3285 const ParsedAttr *MSPropertyAttr =
3287
3288 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3289 // The Microsoft extension __interface only permits public member functions
3290 // and prohibits constructors, destructors, operators, non-public member
3291 // functions, static methods and data members.
3292 unsigned InvalidDecl;
3293 bool ShowDeclName = true;
3294 if (!isFunc &&
3295 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3296 InvalidDecl = 0;
3297 else if (!isFunc)
3298 InvalidDecl = 1;
3299 else if (AS != AS_public)
3300 InvalidDecl = 2;
3302 InvalidDecl = 3;
3303 else switch (Name.getNameKind()) {
3305 InvalidDecl = 4;
3306 ShowDeclName = false;
3307 break;
3308
3310 InvalidDecl = 5;
3311 ShowDeclName = false;
3312 break;
3313
3316 InvalidDecl = 6;
3317 break;
3318
3319 default:
3320 InvalidDecl = 0;
3321 break;
3322 }
3323
3324 if (InvalidDecl) {
3325 if (ShowDeclName)
3326 Diag(Loc, diag::err_invalid_member_in_interface)
3327 << (InvalidDecl-1) << Name;
3328 else
3329 Diag(Loc, diag::err_invalid_member_in_interface)
3330 << (InvalidDecl-1) << "";
3331 return nullptr;
3332 }
3333 }
3334
3335 // C++ 9.2p6: A member shall not be declared to have automatic storage
3336 // duration (auto, register) or with the extern storage-class-specifier.
3337 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3338 // data members and cannot be applied to names declared const or static,
3339 // and cannot be applied to reference members.
3340 switch (DS.getStorageClassSpec()) {
3344 break;
3346 if (isFunc) {
3347 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3348
3349 // FIXME: It would be nicer if the keyword was ignored only for this
3350 // declarator. Otherwise we could get follow-up errors.
3352 }
3353 break;
3354 default:
3356 diag::err_storageclass_invalid_for_member);
3358 break;
3359 }
3360
3361 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3363 !isFunc);
3364
3365 if (DS.hasConstexprSpecifier() && isInstField) {
3367 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3368 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3369 if (InitStyle == ICIS_NoInit) {
3370 B << 0 << 0;
3372 B << FixItHint::CreateRemoval(ConstexprLoc);
3373 else {
3374 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3376 const char *PrevSpec;
3377 unsigned DiagID;
3378 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3379 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3380 (void)Failed;
3381 assert(!Failed && "Making a constexpr member const shouldn't fail");
3382 }
3383 } else {
3384 B << 1;
3385 const char *PrevSpec;
3386 unsigned DiagID;
3388 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3389 Context.getPrintingPolicy())) {
3391 "This is the only DeclSpec that should fail to be applied");
3392 B << 1;
3393 } else {
3394 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3395 isInstField = false;
3396 }
3397 }
3398 }
3399
3401 if (isInstField) {
3402 CXXScopeSpec &SS = D.getCXXScopeSpec();
3403
3404 // Data members must have identifiers for names.
3405 if (!Name.isIdentifier()) {
3406 Diag(Loc, diag::err_bad_variable_name)
3407 << Name;
3408 return nullptr;
3409 }
3410
3411 IdentifierInfo *II = Name.getAsIdentifierInfo();
3412
3413 // Member field could not be with "template" keyword.
3414 // So TemplateParameterLists should be empty in this case.
3415 if (TemplateParameterLists.size()) {
3416 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3417 if (TemplateParams->size()) {
3418 // There is no such thing as a member field template.
3419 Diag(D.getIdentifierLoc(), diag::err_template_member)
3420 << II
3421 << SourceRange(TemplateParams->getTemplateLoc(),
3422 TemplateParams->getRAngleLoc());
3423 } else {
3424 // There is an extraneous 'template<>' for this member.
3425 Diag(TemplateParams->getTemplateLoc(),
3426 diag::err_template_member_noparams)
3427 << II
3428 << SourceRange(TemplateParams->getTemplateLoc(),
3429 TemplateParams->getRAngleLoc());
3430 }
3431 return nullptr;
3432 }
3433
3434 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3435 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3436 << II
3440 D.SetIdentifier(II, Loc);
3441 }
3442
3443 if (SS.isSet() && !SS.isInvalid()) {
3444 // The user provided a superfluous scope specifier inside a class
3445 // definition:
3446 //
3447 // class X {
3448 // int X::member;
3449 // };
3450 if (DeclContext *DC = computeDeclContext(SS, false))
3451 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3452 D.getName().getKind() ==
3453 UnqualifiedIdKind::IK_TemplateId);
3454 else
3455 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3456 << Name << SS.getRange();
3457
3458 SS.clear();
3459 }
3460
3461 if (MSPropertyAttr) {
3462 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3463 BitWidth, InitStyle, AS, *MSPropertyAttr);
3464 if (!Member)
3465 return nullptr;
3466 isInstField = false;
3467 } else {
3468 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3469 BitWidth, InitStyle, AS);
3470 if (!Member)
3471 return nullptr;
3472 }
3473
3474 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3475 } else {
3476 Member = HandleDeclarator(S, D, TemplateParameterLists);
3477 if (!Member)
3478 return nullptr;
3479
3480 // Non-instance-fields can't have a bitfield.
3481 if (BitWidth) {
3482 if (Member->isInvalidDecl()) {
3483 // don't emit another diagnostic.
3484 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3485 // C++ 9.6p3: A bit-field shall not be a static member.
3486 // "static member 'A' cannot be a bit-field"
3487 Diag(Loc, diag::err_static_not_bitfield)
3488 << Name << BitWidth->getSourceRange();
3489 } else if (isa<TypedefDecl>(Member)) {
3490 // "typedef member 'x' cannot be a bit-field"
3491 Diag(Loc, diag::err_typedef_not_bitfield)
3492 << Name << BitWidth->getSourceRange();
3493 } else {
3494 // A function typedef ("typedef int f(); f a;").
3495 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3496 Diag(Loc, diag::err_not_integral_type_bitfield)
3497 << Name << cast<ValueDecl>(Member)->getType()
3498 << BitWidth->getSourceRange();
3499 }
3500
3501 BitWidth = nullptr;
3502 Member->setInvalidDecl();
3503 }
3504
3505 NamedDecl *NonTemplateMember = Member;
3506 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3507 NonTemplateMember = FunTmpl->getTemplatedDecl();
3508 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3509 NonTemplateMember = VarTmpl->getTemplatedDecl();
3510
3511 Member->setAccess(AS);
3512
3513 // If we have declared a member function template or static data member
3514 // template, set the access of the templated declaration as well.
3515 if (NonTemplateMember != Member)
3516 NonTemplateMember->setAccess(AS);
3517
3518 // C++ [temp.deduct.guide]p3:
3519 // A deduction guide [...] for a member class template [shall be
3520 // declared] with the same access [as the template].
3521 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3522 auto *TD = DG->getDeducedTemplate();
3523 // Access specifiers are only meaningful if both the template and the
3524 // deduction guide are from the same scope.
3525 if (AS != TD->getAccess() &&
3526 TD->getDeclContext()->getRedeclContext()->Equals(
3527 DG->getDeclContext()->getRedeclContext())) {
3528 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3529 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3530 << TD->getAccess();
3531 const AccessSpecDecl *LastAccessSpec = nullptr;
3532 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3533 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3534 LastAccessSpec = AccessSpec;
3535 }
3536 assert(LastAccessSpec && "differing access with no access specifier");
3537 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3538 << AS;
3539 }
3540 }
3541 }
3542
3543 if (VS.isOverrideSpecified())
3544 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3546 if (VS.isFinalSpecified())
3547 Member->addAttr(FinalAttr::Create(
3549 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3550
3551 if (VS.getLastLocation().isValid()) {
3552 // Update the end location of a method that has a virt-specifiers.
3553 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3554 MD->setRangeEnd(VS.getLastLocation());
3555 }
3556
3557 CheckOverrideControl(Member);
3558
3559 assert((Name || isInstField) && "No identifier for non-field ?");
3560
3561 if (isInstField) {
3563 FieldCollector->Add(FD);
3564
3565 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3566 // Remember all explicit private FieldDecls that have a name, no side
3567 // effects and are not part of a dependent type declaration.
3568 if (!FD->isImplicit() && FD->getDeclName() &&
3569 FD->getAccess() == AS_private &&
3570 !FD->hasAttr<UnusedAttr>() &&
3571 !FD->getParent()->isDependentContext() &&
3573 UnusedPrivateFields.insert(FD);
3574 }
3575 }
3576
3577 return Member;
3578}
3579
3580namespace {
3581 class UninitializedFieldVisitor
3582 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3583 Sema &S;
3584 // List of Decls to generate a warning on. Also remove Decls that become
3585 // initialized.
3586 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3587 // List of base classes of the record. Classes are removed after their
3588 // initializers.
3589 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3590 // Vector of decls to be removed from the Decl set prior to visiting the
3591 // nodes. These Decls may have been initialized in the prior initializer.
3593 // If non-null, add a note to the warning pointing back to the constructor.
3594 const CXXConstructorDecl *Constructor;
3595 // Variables to hold state when processing an initializer list. When
3596 // InitList is true, special case initialization of FieldDecls matching
3597 // InitListFieldDecl.
3598 bool InitList;
3599 FieldDecl *InitListFieldDecl;
3600 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3601
3602 public:
3604 UninitializedFieldVisitor(Sema &S,
3605 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3606 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3607 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3608 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3609
3610 // Returns true if the use of ME is not an uninitialized use.
3611 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3612 bool CheckReferenceOnly) {
3614 bool ReferenceField = false;
3615 while (ME) {
3616 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3617 if (!FD)
3618 return false;
3619 Fields.push_back(FD);
3620 if (FD->getType()->isReferenceType())
3621 ReferenceField = true;
3622 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3623 }
3624
3625 // Binding a reference to an uninitialized field is not an
3626 // uninitialized use.
3627 if (CheckReferenceOnly && !ReferenceField)
3628 return true;
3629
3630 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3631 // Discard the first field since it is the field decl that is being
3632 // initialized.
3633 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3634 UsedFieldIndex.push_back(FD->getFieldIndex());
3635
3636 for (auto UsedIter = UsedFieldIndex.begin(),
3637 UsedEnd = UsedFieldIndex.end(),
3638 OrigIter = InitFieldIndex.begin(),
3639 OrigEnd = InitFieldIndex.end();
3640 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3641 if (*UsedIter < *OrigIter)
3642 return true;
3643 if (*UsedIter > *OrigIter)
3644 break;
3645 }
3646
3647 return false;
3648 }
3649
3650 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3651 bool AddressOf) {
3652 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3653 return;
3654
3655 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3656 // or union.
3657 MemberExpr *FieldME = ME;
3658
3659 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3660
3661 Expr *Base = ME;
3662 while (MemberExpr *SubME =
3663 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3664
3665 if (isa<VarDecl>(SubME->getMemberDecl()))
3666 return;
3667
3668 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3669 if (!FD->isAnonymousStructOrUnion())
3670 FieldME = SubME;
3671
3672 if (!FieldME->getType().isPODType(S.Context))
3673 AllPODFields = false;
3674
3675 Base = SubME->getBase();
3676 }
3677
3678 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3679 Visit(Base);
3680 return;
3681 }
3682
3683 if (AddressOf && AllPODFields)
3684 return;
3685
3686 ValueDecl* FoundVD = FieldME->getMemberDecl();
3687
3688 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3689 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3690 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3691 }
3692
3693 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3694 QualType T = BaseCast->getType();
3695 if (T->isPointerType() &&
3696 BaseClasses.count(T->getPointeeType())) {
3697 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3698 << T->getPointeeType() << FoundVD;
3699 }
3700 }
3701 }
3702
3703 if (!Decls.count(FoundVD))
3704 return;
3705
3706 const bool IsReference = FoundVD->getType()->isReferenceType();
3707
3708 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3709 // Special checking for initializer lists.
3710 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3711 return;
3712 }
3713 } else {
3714 // Prevent double warnings on use of unbounded references.
3715 if (CheckReferenceOnly && !IsReference)
3716 return;
3717 }
3718
3719 unsigned diag = IsReference
3720 ? diag::warn_reference_field_is_uninit
3721 : diag::warn_field_is_uninit;
3722 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3723 if (Constructor)
3724 S.Diag(Constructor->getLocation(),
3725 diag::note_uninit_in_this_constructor)
3726 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3727
3728 }
3729
3730 void HandleValue(Expr *E, bool AddressOf) {
3731 E = E->IgnoreParens();
3732
3733 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3734 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3735 AddressOf /*AddressOf*/);
3736 return;
3737 }
3738
3739 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3740 Visit(CO->getCond());
3741 HandleValue(CO->getTrueExpr(), AddressOf);
3742 HandleValue(CO->getFalseExpr(), AddressOf);
3743 return;
3744 }
3745
3746 if (BinaryConditionalOperator *BCO =
3747 dyn_cast<BinaryConditionalOperator>(E)) {
3748 Visit(BCO->getCond());
3749 HandleValue(BCO->getFalseExpr(), AddressOf);
3750 return;
3751 }
3752
3753 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3754 HandleValue(OVE->getSourceExpr(), AddressOf);
3755 return;
3756 }
3757
3758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3759 switch (BO->getOpcode()) {
3760 default:
3761 break;
3762 case(BO_PtrMemD):
3763 case(BO_PtrMemI):
3764 HandleValue(BO->getLHS(), AddressOf);
3765 Visit(BO->getRHS());
3766 return;
3767 case(BO_Comma):
3768 Visit(BO->getLHS());
3769 HandleValue(BO->getRHS(), AddressOf);
3770 return;
3771 }
3772 }
3773
3774 Visit(E);
3775 }
3776
3777 void CheckInitListExpr(InitListExpr *ILE) {
3778 InitFieldIndex.push_back(0);
3779 for (auto Child : ILE->children()) {
3780 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3781 CheckInitListExpr(SubList);
3782 } else {
3783 Visit(Child);
3784 }
3785 ++InitFieldIndex.back();
3786 }
3787 InitFieldIndex.pop_back();
3788 }
3789
3790 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3791 FieldDecl *Field, const Type *BaseClass) {
3792 // Remove Decls that may have been initialized in the previous
3793 // initializer.
3794 for (ValueDecl* VD : DeclsToRemove)
3795 Decls.erase(VD);
3796 DeclsToRemove.clear();
3797
3798 Constructor = FieldConstructor;
3799 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3800
3801 if (ILE && Field) {
3802 InitList = true;
3803 InitListFieldDecl = Field;
3804 InitFieldIndex.clear();
3805 CheckInitListExpr(ILE);
3806 } else {
3807 InitList = false;
3808 Visit(E);
3809 }
3810
3811 if (Field)
3812 Decls.erase(Field);
3813 if (BaseClass)
3814 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3815 }
3816
3817 void VisitMemberExpr(MemberExpr *ME) {
3818 // All uses of unbounded reference fields will warn.
3819 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3820 }
3821
3822 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3823 if (E->getCastKind() == CK_LValueToRValue) {
3824 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3825 return;
3826 }
3827
3828 Inherited::VisitImplicitCastExpr(E);
3829 }
3830
3831 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3832 if (E->getConstructor()->isCopyConstructor()) {
3833 Expr *ArgExpr = E->getArg(0);
3834 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3835 if (ILE->getNumInits() == 1)
3836 ArgExpr = ILE->getInit(0);
3837 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3838 if (ICE->getCastKind() == CK_NoOp)
3839 ArgExpr = ICE->getSubExpr();
3840 HandleValue(ArgExpr, false /*AddressOf*/);
3841 return;
3842 }
3843 Inherited::VisitCXXConstructExpr(E);
3844 }
3845
3846 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3847 Expr *Callee = E->getCallee();
3848 if (isa<MemberExpr>(Callee)) {
3849 HandleValue(Callee, false /*AddressOf*/);
3850 for (auto Arg : E->arguments())
3851 Visit(Arg);
3852 return;
3853 }
3854
3855 Inherited::VisitCXXMemberCallExpr(E);
3856 }
3857
3858 void VisitCallExpr(CallExpr *E) {
3859 // Treat std::move as a use.
3860 if (E->isCallToStdMove()) {
3861 HandleValue(E->getArg(0), /*AddressOf=*/false);
3862 return;
3863 }
3864
3865 Inherited::VisitCallExpr(E);
3866 }
3867
3868 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3869 Expr *Callee = E->getCallee();
3870
3871 if (isa<UnresolvedLookupExpr>(Callee))
3872 return Inherited::VisitCXXOperatorCallExpr(E);
3873
3874 Visit(Callee);
3875 for (auto Arg : E->arguments())
3876 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3877 }
3878
3879 void VisitBinaryOperator(BinaryOperator *E) {
3880 // If a field assignment is detected, remove the field from the
3881 // uninitiailized field set.
3882 if (E->getOpcode() == BO_Assign)
3883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3884 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3885 if (!FD->getType()->isReferenceType())
3886 DeclsToRemove.push_back(FD);
3887
3888 if (E->isCompoundAssignmentOp()) {
3889 HandleValue(E->getLHS(), false /*AddressOf*/);
3890 Visit(E->getRHS());
3891 return;
3892 }
3893
3894 Inherited::VisitBinaryOperator(E);
3895 }
3896
3897 void VisitUnaryOperator(UnaryOperator *E) {
3898 if (E->isIncrementDecrementOp()) {
3899 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3900 return;
3901 }
3902 if (E->getOpcode() == UO_AddrOf) {
3903 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3904 HandleValue(ME->getBase(), true /*AddressOf*/);
3905 return;
3906 }
3907 }
3908
3909 Inherited::VisitUnaryOperator(E);
3910 }
3911 };
3912
3913 // Diagnose value-uses of fields to initialize themselves, e.g.
3914 // foo(foo)
3915 // where foo is not also a parameter to the constructor.
3916 // Also diagnose across field uninitialized use such as
3917 // x(y), y(x)
3918 // TODO: implement -Wuninitialized and fold this into that framework.
3919 static void DiagnoseUninitializedFields(
3920 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3921
3922 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3923 Constructor->getLocation())) {
3924 return;
3925 }
3926
3927 if (Constructor->isInvalidDecl())
3928 return;
3929
3930 const CXXRecordDecl *RD = Constructor->getParent();
3931
3932 if (RD->isDependentContext())
3933 return;
3934
3935 // Holds fields that are uninitialized.
3936 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3937
3938 // At the beginning, all fields are uninitialized.
3939 for (auto *I : RD->decls()) {
3940 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3941 UninitializedFields.insert(FD);
3942 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3943 UninitializedFields.insert(IFD->getAnonField());
3944 }
3945 }
3946
3947 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3948 for (auto I : RD->bases())
3949 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3950
3951 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3952 return;
3953
3954 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3955 UninitializedFields,
3956 UninitializedBaseClasses);
3957
3958 for (const auto *FieldInit : Constructor->inits()) {
3959 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3960 break;
3961
3962 Expr *InitExpr = FieldInit->getInit();
3963 if (!InitExpr)
3964 continue;
3965
3967 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3968 InitExpr = Default->getExpr();
3969 if (!InitExpr)
3970 continue;
3971 // In class initializers will point to the constructor.
3972 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3973 FieldInit->getAnyMember(),
3974 FieldInit->getBaseClass());
3975 } else {
3976 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3977 FieldInit->getAnyMember(),
3978 FieldInit->getBaseClass());
3979 }
3980 }
3981 }
3982} // namespace
3983
3984/// Enter a new C++ default initializer scope. After calling this, the
3985/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3986/// parsing or instantiating the initializer failed.
3988 // Create a synthetic function scope to represent the call to the constructor
3989 // that notionally surrounds a use of this initializer.
3990 PushFunctionScope();
3991}
3992
3994 if (!D.isFunctionDeclarator())
3995 return;
3996 auto &FTI = D.getFunctionTypeInfo();
3997 if (!FTI.Params)
3998 return;
3999 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4000 FTI.NumParams)) {
4001 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4002 if (ParamDecl->getDeclName())
4003 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4004 }
4005}
4006
4008 return ActOnRequiresClause(ConstraintExpr);
4009}
4010
4012 if (ConstraintExpr.isInvalid())
4013 return ExprError();
4014
4015 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4016 if (ConstraintExpr.isInvalid())
4017 return ExprError();
4018
4019 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4020 UPPC_RequiresClause))
4021 return ExprError();
4022
4023 return ConstraintExpr;
4024}
4025
4026/// This is invoked after parsing an in-class initializer for a
4027/// non-static C++ class member, and after instantiating an in-class initializer
4028/// in a class template. Such actions are deferred until the class is complete.
4030 SourceLocation InitLoc,
4031 Expr *InitExpr) {
4032 // Pop the notional constructor scope we created earlier.
4033 PopFunctionScopeInfo(nullptr, D);
4034
4035 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4036 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4037 "must set init style when field is created");
4038
4039 if (!InitExpr) {
4040 D->setInvalidDecl();
4041 if (FD)
4043 return;
4044 }
4045
4046 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4047 FD->setInvalidDecl();
4049 return;
4050 }
4051
4052 ExprResult Init = InitExpr;
4053 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4054 InitializedEntity Entity =
4056 InitializationKind Kind =
4059 InitExpr->getBeginLoc(),
4060 InitExpr->getEndLoc())
4061 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4062 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4063 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4064 if (Init.isInvalid()) {
4065 FD->setInvalidDecl();
4066 return;
4067 }
4068 }
4069
4070 // C++11 [class.base.init]p7:
4071 // The initialization of each base and member constitutes a
4072 // full-expression.
4073 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4074 if (Init.isInvalid()) {
4075 FD->setInvalidDecl();
4076 return;
4077 }
4078
4079 InitExpr = Init.get();
4080
4081 FD->setInClassInitializer(InitExpr);
4082}
4083
4084/// Find the direct and/or virtual base specifiers that
4085/// correspond to the given base type, for use in base initialization
4086/// within a constructor.
4087static bool FindBaseInitializer(Sema &SemaRef,
4088 CXXRecordDecl *ClassDecl,
4089 QualType BaseType,
4090 const CXXBaseSpecifier *&DirectBaseSpec,
4091 const CXXBaseSpecifier *&VirtualBaseSpec) {
4092 // First, check for a direct base class.
4093 DirectBaseSpec = nullptr;
4094 for (const auto &Base : ClassDecl->bases()) {
4095 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4096 // We found a direct base of this type. That's what we're
4097 // initializing.
4098 DirectBaseSpec = &Base;
4099 break;
4100 }
4101 }
4102
4103 // Check for a virtual base class.
4104 // FIXME: We might be able to short-circuit this if we know in advance that
4105 // there are no virtual bases.
4106 VirtualBaseSpec = nullptr;
4107 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4108 // We haven't found a base yet; search the class hierarchy for a
4109 // virtual base class.
4110 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4111 /*DetectVirtual=*/false);
4112 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4113 SemaRef.Context.getTypeDeclType(ClassDecl),
4114 BaseType, Paths)) {
4115 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4116 Path != Paths.end(); ++Path) {
4117 if (Path->back().Base->isVirtual()) {
4118 VirtualBaseSpec = Path->back().Base;
4119 break;
4120 }
4121 }
4122 }
4123 }
4124
4125 return DirectBaseSpec || VirtualBaseSpec;
4126}
4127
4128/// Handle a C++ member initializer using braced-init-list syntax.
4131 Scope *S,
4132 CXXScopeSpec &SS,
4133 IdentifierInfo *MemberOrBase,
4134 ParsedType TemplateTypeTy,
4135 const DeclSpec &DS,
4136 SourceLocation IdLoc,
4137 Expr *InitList,
4138 SourceLocation EllipsisLoc) {
4139 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4140 DS, IdLoc, InitList,
4141 EllipsisLoc);
4142}
4143
4144/// Handle a C++ member initializer using parentheses syntax.
4147 Scope *S,
4148 CXXScopeSpec &SS,
4149 IdentifierInfo *MemberOrBase,
4150 ParsedType TemplateTypeTy,
4151 const DeclSpec &DS,
4152 SourceLocation IdLoc,
4153 SourceLocation LParenLoc,
4154 ArrayRef<Expr *> Args,
4155 SourceLocation RParenLoc,
4156 SourceLocation EllipsisLoc) {
4157 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4158 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4159 DS, IdLoc, List, EllipsisLoc);
4160}
4161
4162namespace {
4163
4164// Callback to only accept typo corrections that can be a valid C++ member
4165// initializer: either a non-static field member or a base class.
4166class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4167public:
4168 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4169 : ClassDecl(ClassDecl) {}
4170
4171 bool ValidateCandidate(const TypoCorrection &candidate) override {
4172 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4173 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4174 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4175 return isa<TypeDecl>(ND);
4176 }
4177 return false;
4178 }
4179
4180 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4181 return std::make_unique<MemInitializerValidatorCCC>(*this);
4182 }
4183
4184private:
4185 CXXRecordDecl *ClassDecl;
4186};
4187
4188}
4189
4190ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4191 CXXScopeSpec &SS,
4192 ParsedType TemplateTypeTy,
4193 IdentifierInfo *MemberOrBase) {
4194 if (SS.getScopeRep() || TemplateTypeTy)
4195 return nullptr;
4196 for (auto *D : ClassDecl->lookup(MemberOrBase))
4197 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4198 return cast<ValueDecl>(D);
4199 return nullptr;
4200}
4201
4202/// Handle a C++ member initializer.
4205 Scope *S,
4206 CXXScopeSpec &SS,
4207 IdentifierInfo *MemberOrBase,
4208 ParsedType TemplateTypeTy,
4209 const DeclSpec &DS,
4210 SourceLocation IdLoc,
4211 Expr *Init,
4212 SourceLocation EllipsisLoc) {
4213 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4214 /*RecoverUncorrectedTypos=*/true);
4215 if (!Res.isUsable())
4216 return true;
4217 Init = Res.get();
4218
4219 if (!ConstructorD)
4220 return true;
4221
4222 AdjustDeclIfTemplate(ConstructorD);
4223
4224 CXXConstructorDecl *Constructor
4225 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4226 if (!Constructor) {
4227 // The user wrote a constructor initializer on a function that is
4228 // not a C++ constructor. Ignore the error for now, because we may
4229 // have more member initializers coming; we'll diagnose it just
4230 // once in ActOnMemInitializers.
4231 return true;
4232 }
4233
4234 CXXRecordDecl *ClassDecl = Constructor->getParent();
4235
4236 // C++ [class.base.init]p2:
4237 // Names in a mem-initializer-id are looked up in the scope of the
4238 // constructor's class and, if not found in that scope, are looked
4239 // up in the scope containing the constructor's definition.
4240 // [Note: if the constructor's class contains a member with the
4241 // same name as a direct or virtual base class of the class, a
4242 // mem-initializer-id naming the member or base class and composed
4243 // of a single identifier refers to the class member. A
4244 // mem-initializer-id for the hidden base class may be specified
4245 // using a qualified name. ]
4246
4247 // Look for a member, first.
4248 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4249 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4250 if (EllipsisLoc.isValid())
4251 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4252 << MemberOrBase
4253 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4254
4255 return BuildMemberInitializer(Member, Init, IdLoc);
4256 }
4257 // It didn't name a member, so see if it names a class.
4258 QualType BaseType;
4259 TypeSourceInfo *TInfo = nullptr;
4260
4261 if (TemplateTypeTy) {
4262 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4263 if (BaseType.isNull())
4264 return true;
4265 } else if (DS.getTypeSpecType() == TST_decltype) {
4266 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4267 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4268 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4269 return true;
4270 } else {
4271 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4272 LookupParsedName(R, S, &SS);
4273
4274 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4275 if (!TyD) {
4276 if (R.isAmbiguous()) return true;
4277
4278 // We don't want access-control diagnostics here.
4280
4281 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4282 bool NotUnknownSpecialization = false;
4283 DeclContext *DC = computeDeclContext(SS, false);
4284 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4285 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4286
4287 if (!NotUnknownSpecialization) {
4288 // When the scope specifier can refer to a member of an unknown
4289 // specialization, we take it as a type name.
4290 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4291 SS.getWithLocInContext(Context),
4292 *MemberOrBase, IdLoc);
4293 if (BaseType.isNull())
4294 return true;
4295
4296 TInfo = Context.CreateTypeSourceInfo(BaseType);
4299 if (!TL.isNull()) {
4300 TL.setNameLoc(IdLoc);
4302 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4303 }
4304
4305 R.clear();
4306 R.setLookupName(MemberOrBase);
4307 }
4308 }
4309
4310 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4311 auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>();
4312 if (UnqualifiedBase) {
4313 Diag(IdLoc, diag::ext_unqualified_base_class)
4314 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4315 BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
4316 }
4317 }
4318
4319 // If no results were found, try to correct typos.
4320 TypoCorrection Corr;
4321 MemInitializerValidatorCCC CCC(ClassDecl);
4322 if (R.empty() && BaseType.isNull() &&
4323 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4324 CCC, CTK_ErrorRecovery, ClassDecl))) {
4326 // We have found a non-static data member with a similar
4327 // name to what was typed; complain and initialize that
4328 // member.
4329 diagnoseTypo(Corr,
4330 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4331 << MemberOrBase << true);
4332 return BuildMemberInitializer(Member, Init, IdLoc);
4333 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4334 const CXXBaseSpecifier *DirectBaseSpec;
4335 const CXXBaseSpecifier *VirtualBaseSpec;
4336 if (FindBaseInitializer(*this, ClassDecl,
4337 Context.getTypeDeclType(Type),
4338 DirectBaseSpec, VirtualBaseSpec)) {
4339 // We have found a direct or virtual base class with a
4340 // similar name to what was typed; complain and initialize
4341 // that base class.
4342 diagnoseTypo(Corr,
4343 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4344 << MemberOrBase << false,
4345 PDiag() /*Suppress note, we provide our own.*/);
4346
4347 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4348 : VirtualBaseSpec;
4349 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4350 << BaseSpec->getType() << BaseSpec->getSourceRange();
4351
4352 TyD = Type;
4353 }
4354 }
4355 }
4356
4357 if (!TyD && BaseType.isNull()) {
4358 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4359 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4360 return true;
4361 }
4362 }
4363
4364 if (BaseType.isNull()) {
4365 BaseType = Context.getTypeDeclType(TyD);
4366 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4367 if (SS.isSet()) {
4368 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4369 BaseType);
4370 TInfo = Context.CreateTypeSourceInfo(BaseType);
4372 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4374 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4375 }
4376 }
4377 }
4378
4379 if (!TInfo)
4380 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4381
4382 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4383}
4384
4387 SourceLocation IdLoc) {
4388 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4389 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4390 assert((DirectMember || IndirectMember) &&
4391 "Member must be a FieldDecl or IndirectFieldDecl");
4392
4393 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4394 return true;
4395
4396 if (Member->isInvalidDecl())
4397 return true;
4398
4399 MultiExprArg Args;
4400 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4401 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4402 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4403 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4404 } else {
4405 // Template instantiation doesn't reconstruct ParenListExprs for us.
4406 Args = Init;
4407 }
4408
4409 SourceRange InitRange = Init->getSourceRange();
4410
4411 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4412 // Can't check initialization for a member of dependent type or when
4413 // any of the arguments are type-dependent expressions.
4414 DiscardCleanupsInEvaluationContext();
4415 } else {
4416 bool InitList = false;
4417 if (isa<InitListExpr>(Init)) {
4418 InitList = true;
4419 Args = Init;
4420 }
4421
4422 // Initialize the member.
4423 InitializedEntity MemberEntity =
4424 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4425 : InitializedEntity::InitializeMember(IndirectMember,
4426 nullptr);
4427 InitializationKind Kind =
4429 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4430 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4431 InitRange.getEnd());
4432
4433 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4434 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4435 nullptr);
4436 if (!MemberInit.isInvalid()) {
4437 // C++11 [class.base.init]p7:
4438 // The initialization of each base and member constitutes a
4439 // full-expression.
4440 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4441 /*DiscardedValue*/ false);
4442 }
4443
4444 if (MemberInit.isInvalid()) {
4445 // Args were sensible expressions but we couldn't initialize the member
4446 // from them. Preserve them in a RecoveryExpr instead.
4447 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4448 Member->getType())
4449 .get();
4450 if (!Init)
4451 return true;
4452 } else {
4453 Init = MemberInit.get();
4454 }
4455 }
4456
4457 if (DirectMember) {
4458 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4459 InitRange.getBegin(), Init,
4460 InitRange.getEnd());
4461 } else {
4462 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4463 InitRange.getBegin(), Init,
4464 InitRange.getEnd());
4465 }
4466}
4467
4470 CXXRecordDecl *ClassDecl) {
4472 if (!LangOpts.CPlusPlus11)
4473 return Diag(NameLoc, diag::err_delegating_ctor)
4474 << TInfo->getTypeLoc().getLocalSourceRange();
4475 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4476
4477 bool InitList = true;
4478 MultiExprArg Args = Init;
4479 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4480 InitList = false;
4481 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4482 }
4483
4484 SourceRange InitRange = Init->getSourceRange();
4485 // Initialize the object.
4487 QualType(ClassDecl->getTypeForDecl(), 0));
4488 InitializationKind Kind =
4490 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4491 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4492 InitRange.getEnd());
4493 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4494 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4495 Args, nullptr);
4496 if (!DelegationInit.isInvalid()) {
4497 assert((DelegationInit.get()->containsErrors() ||
4498 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4499 "Delegating constructor with no target?");
4500
4501 // C++11 [class.base.init]p7:
4502 // The initialization of each base and member constitutes a
4503 // full-expression.
4504 DelegationInit = ActOnFinishFullExpr(
4505 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4506 }
4507
4508 if (DelegationInit.isInvalid()) {
4509 DelegationInit =
4510 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4511 QualType(ClassDecl->getTypeForDecl(), 0));
4512 if (DelegationInit.isInvalid())
4513 return true;
4514 } else {
4515 // If we are in a dependent context, template instantiation will
4516 // perform this type-checking again. Just save the arguments that we
4517 // received in a ParenListExpr.
4518 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4519 // of the information that we have about the base
4520 // initializer. However, deconstructing the ASTs is a dicey process,
4521 // and this approach is far more likely to get the corner cases right.
4522 if (CurContext->isDependentContext())
4523 DelegationInit = Init;
4524 }
4525
4526 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4527 DelegationInit.getAs<Expr>(),
4528 InitRange.getEnd());
4529}
4530
4533 Expr *Init, CXXRecordDecl *ClassDecl,
4534 SourceLocation EllipsisLoc) {
4535 SourceLocation BaseLoc
4536 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4537
4538 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4539 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4540 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4541
4542 // C++ [class.base.init]p2:
4543 // [...] Unless the mem-initializer-id names a nonstatic data
4544 // member of the constructor's class or a direct or virtual base
4545 // of that class, the mem-initializer is ill-formed. A
4546 // mem-initializer-list can initialize a base class using any
4547 // name that denotes that base class type.
4548
4549 // We can store the initializers in "as-written" form and delay analysis until
4550 // instantiation if the constructor is dependent. But not for dependent
4551 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4552 bool Dependent = CurContext->isDependentContext() &&
4553 (BaseType->isDependentType() || Init->isTypeDependent());
4554
4555 SourceRange InitRange = Init->getSourceRange();
4556 if (EllipsisLoc.isValid()) {
4557 // This is a pack expansion.
4558 if (!BaseType->containsUnexpandedParameterPack()) {
4559 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4560 << SourceRange(BaseLoc, InitRange.getEnd());
4561
4562 EllipsisLoc = SourceLocation();
4563 }
4564 } else {
4565 // Check for any unexpanded parameter packs.
4566 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4567 return true;
4568
4569 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4570 return true;
4571 }
4572
4573 // Check for direct and virtual base classes.
4574 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4575 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4576 if (!Dependent) {
4577 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4578 BaseType))
4579 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4580
4581 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4582 VirtualBaseSpec);
4583
4584 // C++ [base.class.init]p2:
4585 // Unless the mem-initializer-id names a nonstatic data member of the
4586 // constructor's class or a direct or virtual base of that class, the
4587 // mem-initializer is ill-formed.
4588 if (!DirectBaseSpec && !VirtualBaseSpec) {
4589 // If the class has any dependent bases, then it's possible that
4590 // one of those types will resolve to the same type as
4591 // BaseType. Therefore, just treat this as a dependent base
4592 // class initialization. FIXME: Should we try to check the
4593 // initialization anyway? It seems odd.
4594 if (ClassDecl->hasAnyDependentBases())
4595 Dependent = true;
4596 else
4597 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4598 << BaseType << Context.getTypeDeclType(ClassDecl)
4599 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4600 }
4601 }
4602
4603 if (Dependent) {
4604 DiscardCleanupsInEvaluationContext();
4605
4606 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4607 /*IsVirtual=*/false,
4608 InitRange.getBegin(), Init,
4609 InitRange.getEnd(), EllipsisLoc);
4610 }
4611
4612 // C++ [base.class.init]p2:
4613 // If a mem-initializer-id is ambiguous because it designates both
4614 // a direct non-virtual base class and an inherited virtual base
4615 // class, the mem-initializer is ill-formed.
4616 if (DirectBaseSpec && VirtualBaseSpec)
4617 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4618 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4619
4620 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4621 if (!BaseSpec)
4622 BaseSpec = VirtualBaseSpec;
4623
4624 // Initialize the base.
4625 bool InitList = true;
4626 MultiExprArg Args = Init;
4627 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4628 InitList = false;
4629 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4630 }
4631
4632 InitializedEntity BaseEntity =
4633 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4634 InitializationKind Kind =
4635 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4636 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4637 InitRange.getEnd());
4638 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4639 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4640 if (!BaseInit.isInvalid()) {
4641 // C++11 [class.base.init]p7:
4642 // The initialization of each base and member constitutes a
4643 // full-expression.
4644 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4645 /*DiscardedValue*/ false);
4646 }
4647
4648 if (BaseInit.isInvalid()) {
4649 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4650 Args, BaseType);
4651 if (BaseInit.isInvalid())
4652 return true;
4653 } else {
4654 // If we are in a dependent context, template instantiation will
4655 // perform this type-checking again. Just save the arguments that we
4656 // received in a ParenListExpr.
4657 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4658 // of the information that we have about the base
4659 // initializer. However, deconstructing the ASTs is a dicey process,
4660 // and this approach is far more likely to get the corner cases right.
4661 if (CurContext->isDependentContext())
4662 BaseInit = Init;
4663 }
4664
4665 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4666 BaseSpec->isVirtual(),
4667 InitRange.getBegin(),
4668 BaseInit.getAs<Expr>(),
4669 InitRange.getEnd(), EllipsisLoc);
4670}
4671
4672// Create a static_cast<T&&>(expr).
4673static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4674 if (T.isNull()) T = E->getType();
4675 QualType TargetType = SemaRef.BuildReferenceType(
4676 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4677 SourceLocation ExprLoc = E->getBeginLoc();
4678 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4679 TargetType, ExprLoc);
4680
4681 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4682 SourceRange(ExprLoc, ExprLoc),
4683 E->getSourceRange()).get();
4684}
4685
4686/// ImplicitInitializerKind - How an implicit base or member initializer should
4687/// initialize its base or member.
4694
4695static bool
4697 ImplicitInitializerKind ImplicitInitKind,
4698 CXXBaseSpecifier *BaseSpec,
4699 bool IsInheritedVirtualBase,
4700 CXXCtorInitializer *&CXXBaseInit) {
4701 InitializedEntity InitEntity
4702 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4703 IsInheritedVirtualBase);
4704
4705 ExprResult BaseInit;
4706
4707 switch (ImplicitInitKind) {
4708 case IIK_Inherit:
4709 case IIK_Default: {
4710 InitializationKind InitKind
4711 = InitializationKind::CreateDefault(Constructor->getLocation());
4712 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4713 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4714 break;
4715 }
4716
4717 case IIK_Move:
4718 case IIK_Copy: {
4719 bool Moving = ImplicitInitKind == IIK_Move;
4720 ParmVarDecl *Param = Constructor->getParamDecl(0);
4721 QualType ParamType = Param->getType().getNonReferenceType();
4722
4723 Expr *CopyCtorArg =
4725 SourceLocation(), Param, false,
4726 Constructor->getLocation(), ParamType,
4727 VK_LValue, nullptr);
4728
4729 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4730
4731 // Cast to the base class to avoid ambiguities.
4732 QualType ArgTy =
4733 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4734 ParamType.getQualifiers());
4735
4736 if (Moving) {
4737 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4738 }
4739
4740 CXXCastPath BasePath;
4741 BasePath.push_back(BaseSpec);
4742 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4743 CK_UncheckedDerivedToBase,
4744 Moving ? VK_XValue : VK_LValue,
4745 &BasePath).get();
4746
4747 InitializationKind InitKind
4748 = InitializationKind::CreateDirect(Constructor->getLocation(),
4750 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4751 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4752 break;
4753 }
4754 }
4755
4756 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4757 if (BaseInit.isInvalid())
4758 return true;
4759
4760 CXXBaseInit =
4761 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4762 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4763 SourceLocation()),
4764 BaseSpec->isVirtual(),
4766 BaseInit.getAs<Expr>(),
4768 SourceLocation());
4769
4770 return false;
4771}
4772
4773static bool RefersToRValueRef(Expr *MemRef) {
4774 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4775 return Referenced->getType()->isRValueReferenceType();
4776}
4777
4778static bool
4780 ImplicitInitializerKind ImplicitInitKind,
4781 FieldDecl *Field, IndirectFieldDecl *Indirect,
4782 CXXCtorInitializer *&CXXMemberInit) {
4783 if (Field->isInvalidDecl())
4784 return true;
4785
4786 SourceLocation Loc = Constructor->getLocation();
4787
4788 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4789 bool Moving = ImplicitInitKind == IIK_Move;
4790 ParmVarDecl *Param = Constructor->getParamDecl(0);
4791 QualType ParamType = Param->getType().getNonReferenceType();
4792
4793 // Suppress copying zero-width bitfields.
4794 if (Field->isZeroLengthBitField(SemaRef.Context))
4795 return false;
4796
4797 Expr *MemberExprBase =
4799 SourceLocation(), Param, false,
4800 Loc, ParamType, VK_LValue, nullptr);
4801
4802 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4803
4804 if (Moving) {
4805 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4806 }
4807
4808 // Build a reference to this field within the parameter.
4809 CXXScopeSpec SS;
4810 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4812 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4813 : cast<ValueDecl>(Field), AS_public);
4814 MemberLookup.resolveKind();
4815 ExprResult CtorArg
4816 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4817 ParamType, Loc,
4818 /*IsArrow=*/false,
4819 SS,
4820 /*TemplateKWLoc=*/SourceLocation(),
4821 /*FirstQualifierInScope=*/nullptr,
4822 MemberLookup,
4823 /*TemplateArgs=*/nullptr,
4824 /*S*/nullptr);
4825 if (CtorArg.isInvalid())
4826 return true;
4827
4828 // C++11 [class.copy]p15:
4829 // - if a member m has rvalue reference type T&&, it is direct-initialized
4830 // with static_cast<T&&>(x.m);
4831 if (RefersToRValueRef(CtorArg.get())) {
4832 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4833 }
4834
4835 InitializedEntity Entity =
4836 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4837 /*Implicit*/ true)
4838 : InitializedEntity::InitializeMember(Field, nullptr,
4839 /*Implicit*/ true);
4840
4841 // Direct-initialize to use the copy constructor.
4842 InitializationKind InitKind =
4844
4845 Expr *CtorArgE = CtorArg.getAs<Expr>();
4846 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4847 ExprResult MemberInit =
4848 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4849 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4850 if (MemberInit.isInvalid())
4851 return true;
4852
4853 if (Indirect)
4854 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4855 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4856 else
4857 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4858 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4859 return false;
4860 }
4861
4862 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4863 "Unhandled implicit init kind!");
4864
4865 QualType FieldBaseElementType =
4866 SemaRef.Context.getBaseElementType(Field->getType());
4867
4868 if (FieldBaseElementType->isRecordType()) {
4869 InitializedEntity InitEntity =
4870 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4871 /*Implicit*/ true)
4872 : InitializedEntity::InitializeMember(Field, nullptr,
4873 /*Implicit*/ true);
4874 InitializationKind InitKind =
4876
4877 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4878 ExprResult MemberInit =
4879 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4880
4881 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4882 if (MemberInit.isInvalid())
4883 return true;
4884
4885 if (Indirect)
4886 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4887 Indirect, Loc,
4888 Loc,
4889 MemberInit.get(),
4890 Loc);
4891 else
4892 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4893 Field, Loc, Loc,
4894 MemberInit.get(),
4895 Loc);
4896 return false;
4897 }
4898
4899 if (!Field->getParent()->isUnion()) {
4900 if (FieldBaseElementType->isReferenceType()) {
4901 SemaRef.Diag(Constructor->getLocation(),
4902 diag::err_uninitialized_member_in_ctor)
4903 << (int)Constructor->isImplicit()
4904 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4905 << 0 << Field->getDeclName();
4906 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4907 return true;
4908 }
4909
4910 if (FieldBaseElementType.isConstQualified()) {
4911 SemaRef.Diag(Constructor->getLocation(),
4912 diag::err_uninitialized_member_in_ctor)
4913 << (int)Constructor->isImplicit()
4914 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4915 << 1 << Field->getDeclName();
4916 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4917 return true;
4918 }
4919 }
4920
4921 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4922 // ARC and Weak:
4923 // Default-initialize Objective-C pointers to NULL.
4924 CXXMemberInit
4925 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4926 Loc, Loc,
4927 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4928 Loc);
4929 return false;
4930 }
4931
4932 // Nothing to initialize.
4933 CXXMemberInit = nullptr;
4934 return false;
4935}
4936
4937namespace {
4938struct BaseAndFieldInfo {
4939 Sema &S;
4940 CXXConstructorDecl *Ctor;
4941 bool AnyErrorsInInits;
4943 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4945 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4946
4947 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4948 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4949 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4950 if (Ctor->getInheritedConstructor())
4951 IIK = IIK_Inherit;
4952 else if (Generated && Ctor->isCopyConstructor())
4953 IIK = IIK_Copy;
4954 else if (Generated && Ctor->isMoveConstructor())
4955 IIK = IIK_Move;
4956 else
4957 IIK = IIK_Default;
4958 }
4959
4960 bool isImplicitCopyOrMove() const {
4961 switch (IIK) {
4962 case IIK_Copy:
4963 case IIK_Move:
4964 return true;
4965
4966 case IIK_Default:
4967 case IIK_Inherit:
4968 return false;
4969 }
4970
4971 llvm_unreachable("Invalid ImplicitInitializerKind!");
4972 }
4973
4974 bool addFieldInitializer(CXXCtorInitializer *Init) {
4975 AllToInit.push_back(Init);
4976
4977 // Check whether this initializer makes the field "used".
4978 if (Init->getInit()->HasSideEffects(S.Context))
4979 S.UnusedPrivateFields.remove(Init->getAnyMember());
4980
4981 return false;
4982 }
4983
4984 bool isInactiveUnionMember(FieldDecl *Field) {
4985 RecordDecl *Record = Field->getParent();
4986 if (!Record->isUnion())
4987 return false;
4988
4989 if (FieldDecl *Active =
4990 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4991 return Active != Field->getCanonicalDecl();
4992
4993 // In an implicit copy or move constructor, ignore any in-class initializer.
4994 if (isImplicitCopyOrMove())
4995 return true;
4996
4997 // If there's no explicit initialization, the field is active only if it
4998 // has an in-class initializer...
4999 if (Field->hasInClassInitializer())
5000 return false;
5001 // ... or it's an anonymous struct or union whose class has an in-class
5002 // initializer.
5003 if (!Field->isAnonymousStructOrUnion())
5004 return true;
5005 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5006 return !FieldRD->hasInClassInitializer();
5007 }
5008
5009 /// Determine whether the given field is, or is within, a union member
5010 /// that is inactive (because there was an initializer given for a different
5011 /// member of the union, or because the union was not initialized at all).
5012 bool isWithinInactiveUnionMember(FieldDecl *Field,
5013 IndirectFieldDecl *Indirect) {
5014 if (!Indirect)
5015 return isInactiveUnionMember(Field);
5016
5017 for (auto *C : Indirect->chain()) {
5018 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5019 if (Field && isInactiveUnionMember(Field))
5020 return true;
5021 }
5022 return false;
5023 }
5024};
5025}
5026
5027/// Determine whether the given type is an incomplete or zero-lenfgth
5028/// array type.
5030 if (T->isIncompleteArrayType())
5031 return true;
5032
5033 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5034 if (!ArrayT->getSize())
5035 return true;
5036
5037 T = ArrayT->getElementType();
5038 }
5039
5040 return false;
5041}
5042
5043static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5044 FieldDecl *Field,
5045 IndirectFieldDecl *Indirect = nullptr) {
5046 if (Field->isInvalidDecl())
5047 return false;
5048
5049 // Overwhelmingly common case: we have a direct initializer for this field.
5050 if (CXXCtorInitializer *Init =
5051 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5052 return Info.addFieldInitializer(Init);
5053
5054 // C++11 [class.base.init]p8:
5055 // if the entity is a non-static data member that has a
5056 // brace-or-equal-initializer and either
5057 // -- the constructor's class is a union and no other variant member of that
5058 // union is designated by a mem-initializer-id or
5059 // -- the constructor's class is not a union, and, if the entity is a member
5060 // of an anonymous union, no other member of that union is designated by
5061 // a mem-initializer-id,
5062 // the entity is initialized as specified in [dcl.init].
5063 //
5064 // We also apply the same rules to handle anonymous structs within anonymous
5065 // unions.
5066 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5067 return false;
5068
5069 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5070 ExprResult DIE =
5071 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5072 if (DIE.isInvalid())
5073 return true;
5074
5075 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5076 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5077
5078 CXXCtorInitializer *Init;
5079 if (Indirect)
5080 Init = new (SemaRef.Context)
5081 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5082 SourceLocation(), DIE.get(), SourceLocation());
5083 else
5084 Init = new (SemaRef.Context)
5085 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5086 SourceLocation(), DIE.get(), SourceLocation());
5087 return Info.addFieldInitializer(Init);
5088 }
5089
5090 // Don't initialize incomplete or zero-length arrays.
5091 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5092 return false;
5093
5094 // Don't try to build an implicit initializer if there were semantic
5095 // errors in any of the initializers (and therefore we might be
5096 // missing some that the user actually wrote).
5097 if (Info.AnyErrorsInInits)
5098 return false;
5099
5100 CXXCtorInitializer *Init = nullptr;
5101 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5102 Indirect, Init))
5103 return true;
5104
5105 if (!Init)
5106 return false;
5107
5108 return Info.addFieldInitializer(Init);
5109}
5110
5111bool
5114 assert(Initializer->isDelegatingInitializer());
5115 Constructor->setNumCtorInitializers(1);
5116 CXXCtorInitializer **initializer =
5117 new (Context) CXXCtorInitializer*[1];
5118 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5119 Constructor->setCtorInitializers(initializer);
5120
5121 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5122 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5123 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5124 }
5125
5126 DelegatingCtorDecls.push_back(Constructor);
5127
5128 DiagnoseUninitializedFields(*this, Constructor);
5129
5130 return false;
5131}
5132
5133bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5134 ArrayRef<CXXCtorInitializer *> Initializers) {
5135 if (Constructor->isDependentContext()) {
5136 // Just store the initializers as written, they will be checked during
5137 // instantiation.
5138 if (!Initializers.empty()) {
5139 Constructor->setNumCtorInitializers(Initializers.size());
5140 CXXCtorInitializer **baseOrMemberInitializers =
5141 new (Context) CXXCtorInitializer*[Initializers.size()];
5142 memcpy(baseOrMemberInitializers, Initializers.data(),
5143 Initializers.size() * sizeof(CXXCtorInitializer*));
5144 Constructor->setCtorInitializers(baseOrMemberInitializers);
5145 }
5146
5147 // Let template instantiation know whether we had errors.
5148 if (AnyErrors)
5149 Constructor->setInvalidDecl();
5150
5151 return false;
5152 }
5153
5154 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5155
5156 // We need to build the initializer AST according to order of construction
5157 // and not what user specified in the Initializers list.
5158 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5159 if (!ClassDecl)
5160 return true;
5161
5162 bool HadError = false;
5163
5164 for (unsigned i = 0; i < Initializers.size(); i++) {
5165 CXXCtorInitializer *Member = Initializers[i];
5166
5167 if (Member->isBaseInitializer())
5168 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5169 else {
5170 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5171
5172 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5173 for (auto *C : F->chain()) {
5174 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5175 if (FD && FD->getParent()->isUnion())
5176 Info.ActiveUnionMember.insert(std::make_pair(
5178 }
5179 } else if (FieldDecl *FD = Member->getMember()) {
5180 if (FD->getParent()->isUnion())
5181 Info.ActiveUnionMember.insert(std::make_pair(
5183 }
5184 }
5185 }
5186
5187 // Keep track of the direct virtual bases.
5189 for (auto &I : ClassDecl->bases()) {
5190 if (I.isVirtual())
5191 DirectVBases.insert(&I);
5192 }
5193
5194 // Push virtual bases before others.
5195 for (auto &VBase : ClassDecl->vbases()) {
5197 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5198 // [class.base.init]p7, per DR257:
5199 // A mem-initializer where the mem-initializer-id names a virtual base
5200 // class is ignored during execution of a constructor of any class that
5201 // is not the most derived class.
5202 if (ClassDecl->isAbstract()) {
5203 // FIXME: Provide a fixit to remove the base specifier. This requires
5204 // tracking the location of the associated comma for a base specifier.
5205 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5206 << VBase.getType() << ClassDecl;
5207 DiagnoseAbstractType(ClassDecl);
5208 }
5209
5210 Info.AllToInit.push_back(Value);
5211 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5212 // [class.base.init]p8, per DR257:
5213 // If a given [...] base class is not named by a mem-initializer-id
5214 // [...] and the entity is not a virtual base class of an abstract
5215 // class, then [...] the entity is default-initialized.
5216 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5217 CXXCtorInitializer *CXXBaseInit;
5218 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5219 &VBase, IsInheritedVirtualBase,
5220 CXXBaseInit)) {
5221 HadError = true;
5222 continue;
5223 }
5224
5225 Info.AllToInit.push_back(CXXBaseInit);
5226 }
5227 }
5228
5229 // Non-virtual bases.
5230 for (auto &Base : ClassDecl->bases()) {
5231 // Virtuals are in the virtual base list and already constructed.
5232 if (Base.isVirtual())
5233 continue;
5234
5236 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5237 Info.AllToInit.push_back(Value);
5238 } else if (!AnyErrors) {
5239 CXXCtorInitializer *CXXBaseInit;
5240 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5241 &Base, /*IsInheritedVirtualBase=*/false,
5242 CXXBaseInit)) {
5243 HadError = true;
5244 continue;
5245 }
5246
5247 Info.AllToInit.push_back(CXXBaseInit);
5248 }
5249 }
5250
5251 // Fields.
5252 for (auto *Mem : ClassDecl->decls()) {
5253 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5254 // C++ [class.bit]p2:
5255 // A declaration for a bit-field that omits the identifier declares an
5256 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5257 // initialized.
5258 if (F->isUnnamedBitfield())
5259 continue;
5260
5261 // If we're not generating the implicit copy/move constructor, then we'll
5262 // handle anonymous struct/union fields based on their individual
5263 // indirect fields.
5264 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5265 continue;
5266
5267 if (CollectFieldInitializer(*this, Info, F))
5268 HadError = true;
5269 continue;
5270 }
5271
5272 // Beyond this point, we only consider default initialization.
5273 if (Info.isImplicitCopyOrMove())
5274 continue;
5275
5276 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5277 if (F->getType()->isIncompleteArrayType()) {
5278 assert(ClassDecl->hasFlexibleArrayMember() &&
5279 "Incomplete array type is not valid");
5280 continue;
5281 }
5282
5283 // Initialize each field of an anonymous struct individually.
5284 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5285 HadError = true;
5286
5287 continue;
5288 }
5289 }
5290
5291 unsigned NumInitializers = Info.AllToInit.size();
5292 if (NumInitializers > 0) {
5293 Constructor->setNumCtorInitializers(NumInitializers);
5294 CXXCtorInitializer **baseOrMemberInitializers =
5295 new (Context) CXXCtorInitializer*[NumInitializers];
5296 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5297 NumInitializers * sizeof(CXXCtorInitializer*));
5298 Constructor->setCtorInitializers(baseOrMemberInitializers);
5299
5300 // Constructors implicitly reference the base and member
5301 // destructors.
5302 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5303 Constructor->getParent());
5304 }
5305
5306 return HadError;
5307}
5308
5310 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5311 const RecordDecl *RD = RT->getDecl();
5312 if (RD->isAnonymousStructOrUnion()) {
5313 for (auto *Field : RD->fields())
5314 PopulateKeysForFields(Field, IdealInits);
5315 return;
5316 }
5317 }
5318 IdealInits.push_back(Field->getCanonicalDecl());
5319}
5320
5321static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5322 return Context.getCanonicalType(BaseType).getTypePtr();
5323}
5324
5325static const void *GetKeyForMember(ASTContext &Context,
5327 if (!Member->isAnyMemberInitializer())
5328 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5329
5330 return Member->getAnyMember()->getCanonicalDecl();
5331}
5332
5335 const CXXCtorInitializer *Current) {
5336 if (Previous->isAnyMemberInitializer())
5337 Diag << 0 << Previous->getAnyMember();
5338 else
5339 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5340
5341 if (Current->isAnyMemberInitializer())
5342 Diag << 0 << Current->getAnyMember();
5343 else
5344 Diag << 1 << Current->getTypeSourceInfo()->getType();
5345}
5346
5348 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5350 if (Constructor->getDeclContext()->isDependentContext())
5351 return;
5352
5353 // Don't check initializers order unless the warning is enabled at the
5354 // location of at least one initializer.
5355 bool ShouldCheckOrder = false;
5356 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5357 CXXCtorInitializer *Init = Inits[InitIndex];
5358 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5359 Init->getSourceLocation())) {
5360 ShouldCheckOrder = true;
5361 break;
5362 }
5363 }
5364 if (!ShouldCheckOrder)
5365 return;
5366
5367 // Build the list of bases and members in the order that they'll
5368 // actually be initialized. The explicit initializers should be in
5369 // this same order but may be missing things.
5370 SmallVector<const void*, 32> IdealInitKeys;
5371
5372 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5373
5374 // 1. Virtual bases.
5375 for (const auto &VBase : ClassDecl->vbases())
5376 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5377
5378 // 2. Non-virtual bases.
5379 for (const auto &Base : ClassDecl->bases()) {
5380 if (Base.isVirtual())
5381 continue;
5382 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5383 }
5384
5385 // 3. Direct fields.
5386 for (auto *Field : ClassDecl->fields()) {
5387 if (Field->isUnnamedBitfield())
5388 continue;
5389
5390 PopulateKeysForFields(Field, IdealInitKeys);
5391 }
5392
5393 unsigned NumIdealInits = IdealInitKeys.size();
5394 unsigned IdealIndex = 0;
5395
5396 // Track initializers that are in an incorrect order for either a warning or
5397 // note if multiple ones occur.
5398 SmallVector<unsigned> WarnIndexes;
5399 // Correlates the index of an initializer in the init-list to the index of
5400 // the field/base in the class.
5401 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5402
5403 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5404 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5405
5406 // Scan forward to try to find this initializer in the idealized
5407 // initializers list.
5408 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5409 if (InitKey == IdealInitKeys[IdealIndex])
5410 break;
5411
5412 // If we didn't find this initializer, it must be because we
5413 // scanned past it on a previous iteration. That can only
5414 // happen if we're out of order; emit a warning.
5415 if (IdealIndex == NumIdealInits && InitIndex) {
5416 WarnIndexes.push_back(InitIndex);
5417
5418 // Move back to the initializer's location in the ideal list.
5419 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5420 if (InitKey == IdealInitKeys[IdealIndex])
5421 break;
5422
5423 assert(IdealIndex < NumIdealInits &&
5424 "initializer not found in initializer list");
5425 }
5426 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5427 }
5428
5429 if (WarnIndexes.empty())
5430 return;
5431
5432 // Sort based on the ideal order, first in the pair.
5433 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5434
5435 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5436 // emit the diagnostic before we can try adding notes.
5437 {
5439 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5440 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5441 : diag::warn_some_initializers_out_of_order);
5442
5443 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5444 if (CorrelatedInitOrder[I].second == I)
5445 continue;
5446 // Ideally we would be using InsertFromRange here, but clang doesn't
5447 // appear to handle InsertFromRange correctly when the source range is
5448 // modified by another fix-it.
5450 Inits[I]->getSourceRange(),
5453 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5454 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5455 }
5456
5457 // If there is only 1 item out of order, the warning expects the name and
5458 // type of each being added to it.
5459 if (WarnIndexes.size() == 1) {
5460 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5461 Inits[WarnIndexes.front()]);
5462 return;
5463 }
5464 }
5465 // More than 1 item to warn, create notes letting the user know which ones
5466 // are bad.
5467 for (unsigned WarnIndex : WarnIndexes) {
5468 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5469 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5470 diag::note_initializer_out_of_order);
5471 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5472 D << PrevInit->getSourceRange();
5473 }
5474}
5475
5476namespace {
5477bool CheckRedundantInit(Sema &S,
5478 CXXCtorInitializer *Init,
5479 CXXCtorInitializer *&PrevInit) {
5480 if (!PrevInit) {
5481 PrevInit = Init;
5482 return false;
5483 }
5484
5485 if (FieldDecl *Field = Init->getAnyMember())
5486 S.Diag(Init->getSourceLocation(),
5487 diag::err_multiple_mem_initialization)
5488 << Field->getDeclName()
5489 << Init->getSourceRange();
5490 else {
5491 const Type *BaseClass = Init->getBaseClass();
5492 assert(BaseClass && "neither field nor base");
5493 S.Diag(Init->getSourceLocation(),
5494 diag::err_multiple_base_initialization)
5495 << QualType(BaseClass, 0)
5496 << Init->getSourceRange();
5497 }
5498 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5499 << 0 << PrevInit->getSourceRange();
5500
5501 return true;
5502}
5503
5504typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5505typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5506
5507bool CheckRedundantUnionInit(Sema &S,
5508 CXXCtorInitializer *Init,
5509 RedundantUnionMap &Unions) {
5510 FieldDecl *Field = Init->getAnyMember();
5511 RecordDecl *Parent = Field->getParent();
5512 NamedDecl *Child = Field;
5513
5514 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5515 if (Parent->isUnion()) {
5516 UnionEntry &En = Unions[Parent];
5517 if (En.first && En.first != Child) {
5518 S.Diag(Init->getSourceLocation(),
5519 diag::err_multiple_mem_union_initialization)
5520 << Field->getDeclName()
5521 << Init->getSourceRange();
5522 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5523 << 0 << En.second->getSourceRange();
5524 return true;
5525 }
5526 if (!En.first) {
5527 En.first = Child;
5528 En.second = Init;
5529 }
5530 if (!Parent->isAnonymousStructOrUnion())
5531 return false;
5532 }
5533
5534 Child = Parent;
5535 Parent = cast<RecordDecl>(Parent->getDeclContext());
5536 }
5537
5538 return false;
5539}
5540} // namespace
5541
5542/// ActOnMemInitializers - Handle the member initializers for a constructor.
5543void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5544 SourceLocation ColonLoc,
5546 bool AnyErrors) {
5547 if (!ConstructorDecl)
5548 return;
5549
5550 AdjustDeclIfTemplate(ConstructorDecl);
5551
5552 CXXConstructorDecl *Constructor
5553 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5554
5555 if (!Constructor) {
5556 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5557 return;
5558 }
5559
5560 // Mapping for the duplicate initializers check.
5561 // For member initializers, this is keyed with a FieldDecl*.
5562 // For base initializers, this is keyed with a Type*.
5563 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5564
5565 // Mapping for the inconsistent anonymous-union initializers check.
5566 RedundantUnionMap MemberUnions;
5567
5568 bool HadError = false;
5569 for (unsigned i = 0; i < MemInits.size(); i++) {
5570 CXXCtorInitializer *Init = MemInits[i];
5571
5572 // Set the source order index.
5573 Init->setSourceOrder(i);
5574
5575 if (Init->isAnyMemberInitializer()) {
5576 const void *Key = GetKeyForMember(Context, Init);
5577 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5578 CheckRedundantUnionInit(*this, Init, MemberUnions))
5579 HadError = true;
5580 } else if (Init->isBaseInitializer()) {
5581 const void *Key = GetKeyForMember(Context, Init);
5582 if (CheckRedundantInit(*this, Init, Members[Key]))
5583 HadError = true;
5584 } else {
5585 assert(Init->isDelegatingInitializer());
5586 // This must be the only initializer
5587 if (MemInits.size() != 1) {
5588 Diag(Init->getSourceLocation(),
5589 diag::err_delegating_initializer_alone)
5590 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5591 // We will treat this as being the only initializer.
5592 }
5593 SetDelegatingInitializer(Constructor, MemInits[i]);
5594 // Return immediately as the initializer is set.
5595 return;
5596 }
5597 }
5598
5599 if (HadError)
5600 return;
5601
5602 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5603
5604 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5605
5606 DiagnoseUninitializedFields(*this, Constructor);
5607}
5608
5609void
5611 CXXRecordDecl *ClassDecl) {
5612 // Ignore dependent contexts. Also ignore unions, since their members never
5613 // have destructors implicitly called.
5614 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5615 return;
5616
5617 // FIXME: all the access-control diagnostics are positioned on the
5618 // field/base declaration. That's probably good; that said, the
5619 // user might reasonably want to know why the destructor is being
5620 // emitted, and we currently don't say.
5621
5622 // Non-static data members.
5623 for (auto *Field : ClassDecl->fields()) {
5624 if (Field->isInvalidDecl())
5625 continue;
5626
5627 // Don't destroy incomplete or zero-length arrays.
5628 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5629 continue;
5630
5631 QualType FieldType = Context.getBaseElementType(Field->getType());
5632
5633 const RecordType* RT = FieldType->getAs<RecordType>();
5634 if (!RT)
5635 continue;
5636
5637 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5638 if (FieldClassDecl->isInvalidDecl())
5639 continue;
5640 if (FieldClassDecl->hasIrrelevantDestructor())
5641 continue;
5642 // The destructor for an implicit anonymous union member is never invoked.
5643 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5644 continue;
5645
5646 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5647 assert(Dtor && "No dtor found for FieldClassDecl!");
5648 CheckDestructorAccess(Field->getLocation(), Dtor,
5649 PDiag(diag::err_access_dtor_field)
5650 << Field->getDeclName()
5651 << FieldType);
5652
5653 MarkFunctionReferenced(Location, Dtor);
5654 DiagnoseUseOfDecl(Dtor, Location);
5655 }
5656
5657 // We only potentially invoke the destructors of potentially constructed
5658 // subobjects.
5659 bool VisitVirtualBases = !ClassDecl->isAbstract();
5660
5661 // If the destructor exists and has already been marked used in the MS ABI,
5662 // then virtual base destructors have already been checked and marked used.
5663 // Skip checking them again to avoid duplicate diagnostics.
5664 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5665 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5666 if (Dtor && Dtor->isUsed())
5667 VisitVirtualBases = false;
5668 }
5669
5671
5672 // Bases.
5673 for (const auto &Base : ClassDecl->bases()) {
5674 const RecordType *RT = Base.getType()->getAs<RecordType>();
5675 if (!RT)
5676 continue;
5677
5678 // Remember direct virtual bases.
5679 if (Base.isVirtual()) {
5680 if (!VisitVirtualBases)
5681 continue;
5682 DirectVirtualBases.insert(RT);
5683 }
5684
5685 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5686 // If our base class is invalid, we probably can't get its dtor anyway.
5687 if (BaseClassDecl->isInvalidDecl())
5688 continue;
5689 if (BaseClassDecl->hasIrrelevantDestructor())
5690 continue;
5691
5692 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5693 assert(Dtor && "No dtor found for BaseClassDecl!");
5694
5695 // FIXME: caret should be on the start of the class name
5696 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5697 PDiag(diag::err_access_dtor_base)
5698 << Base.getType() << Base.getSourceRange(),
5699 Context.getTypeDeclType(ClassDecl));
5700
5701 MarkFunctionReferenced(Location, Dtor);
5702 DiagnoseUseOfDecl(Dtor, Location);
5703 }
5704
5705 if (VisitVirtualBases)
5706 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5707 &DirectVirtualBases);
5708}
5709
5711 SourceLocation Location, CXXRecordDecl *ClassDecl,
5712 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5713 // Virtual bases.
5714 for (const auto &VBase : ClassDecl->vbases()) {
5715 // Bases are always records in a well-formed non-dependent class.
5716 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5717
5718 // Ignore already visited direct virtual bases.
5719 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5720 continue;
5721
5722 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5723 // If our base class is invalid, we probably can't get its dtor anyway.
5724 if (BaseClassDecl->isInvalidDecl())
5725 continue;
5726 if (BaseClassDecl->hasIrrelevantDestructor())
5727 continue;
5728
5729 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5730 assert(Dtor && "No dtor found for BaseClassDecl!");
5731 if (CheckDestructorAccess(
5732 ClassDecl->getLocation(), Dtor,
5733 PDiag(diag::err_access_dtor_vbase)
5734 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5735 Context.getTypeDeclType(ClassDecl)) ==
5736 AR_accessible) {
5737 CheckDerivedToBaseConversion(
5738 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5739 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5740 SourceRange(), DeclarationName(), nullptr);
5741 }
5742
5743 MarkFunctionReferenced(Location, Dtor);
5744 DiagnoseUseOfDecl(Dtor, Location);
5745 }
5746}
5747
5749 if (!CDtorDecl)
5750 return;
5751
5752 if (CXXConstructorDecl *Constructor
5753 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5754 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5755 DiagnoseUninitializedFields(*this, Constructor);
5756 }
5757}
5758
5760 if (!getLangOpts().CPlusPlus)
5761 return false;
5762
5763 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5764 if (!RD)
5765 return false;
5766
5767 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5768 // class template specialization here, but doing so breaks a lot of code.
5769
5770 // We can't answer whether something is abstract until it has a
5771 // definition. If it's currently being defined, we'll walk back
5772 // over all the declarations when we have a full definition.
5773 const CXXRecordDecl *Def = RD->getDefinition();
5774 if (!Def || Def->isBeingDefined())
5775 return false;
5776
5777 return RD->isAbstract();
5778}
5779
5781 TypeDiagnoser &Diagnoser) {
5782 if (!isAbstractType(Loc, T))
5783 return false;
5784
5785 T = Context.getBaseElementType(T);
5786 Diagnoser.diagnose(*this, Loc, T);
5787 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5788 return true;
5789}
5790
5792 // Check if we've already emitted the list of pure virtual functions
5793 // for this class.
5794 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5795 return;
5796
5797 // If the diagnostic is suppressed, don't emit the notes. We're only
5798 // going to emit them once, so try to attach them to a diagnostic we're
5799 // actually going to show.
5800 if (Diags.isLastDiagnosticIgnored())
5801 return;
5802
5803 CXXFinalOverriderMap FinalOverriders;
5804 RD->getFinalOverriders(FinalOverriders);
5805
5806 // Keep a set of seen pure methods so we won't diagnose the same method
5807 // more than once.
5809
5810 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5811 MEnd = FinalOverriders.end();
5812 M != MEnd;
5813 ++M) {
5814 for (OverridingMethods::iterator SO = M->second.begin(),
5815 SOEnd = M->second.end();
5816 SO != SOEnd; ++SO) {
5817 // C++ [class.abstract]p4:
5818 // A class is abstract if it contains or inherits at least one
5819 // pure virtual function for which the final overrider is pure
5820 // virtual.
5821
5822 //
5823 if (SO->second.size() != 1)
5824 continue;
5825
5826 if (!SO->second.front().Method->isPure())
5827 continue;
5828
5829 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5830 continue;
5831
5832 Diag(SO->second.front().Method->getLocation(),
5833 diag::note_pure_virtual_function)
5834 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5835 }
5836 }
5837
5838 if (!PureVirtualClassDiagSet)
5839 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5840 PureVirtualClassDiagSet->insert(RD);
5841}
5842
5843namespace {
5844struct AbstractUsageInfo {
5845 Sema &S;
5846 CXXRecordDecl *Record;
5847 CanQualType AbstractType;
5848 bool Invalid;
5849
5850 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5851 : S(S), Record(Record),
5852 AbstractType(S.Context.getCanonicalType(
5853 S.Context.getTypeDeclType(Record))),
5854 Invalid(false) {}
5855
5856 void DiagnoseAbstractType() {
5857 if (Invalid) return;
5858 S.DiagnoseAbstractType(Record);
5859 Invalid = true;
5860 }
5861
5862 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5863};
5864
5865struct CheckAbstractUsage {
5866 AbstractUsageInfo &Info;
5867 const NamedDecl *Ctx;
5868
5869 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5870 : Info(Info), Ctx(Ctx) {}
5871
5872 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5873 switch (TL.getTypeLocClass()) {
5874#define ABSTRACT_TYPELOC(CLASS, PARENT)
5875#define TYPELOC(CLASS, PARENT) \
5876 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5877#include "clang/AST/TypeLocNodes.def"
5878 }
5879 }
5880
5881 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5883 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5884 if (!TL.getParam(I))
5885 continue;
5886
5888 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5889 }
5890 }
5891
5892 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5894 }
5895
5897 // Visit the type parameters from a permissive context.
5898 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5899 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5901 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5902 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5903 // TODO: other template argument types?
5904 }
5905 }
5906
5907 // Visit pointee types from a permissive context.
5908#define CheckPolymorphic(Type) \
5909 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5910 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5911 }
5917
5918 /// Handle all the types we haven't given a more specific
5919 /// implementation for above.
5920 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5921 // Every other kind of type that we haven't called out already
5922 // that has an inner type is either (1) sugar or (2) contains that
5923 // inner type in some way as a subobject.
5924 if (TypeLoc Next = TL.getNextTypeLoc())
5925 return Visit(Next, Sel);
5926
5927 // If there's no inner type and we're in a permissive context,
5928 // don't diagnose.
5929 if (Sel == Sema::AbstractNone) return;
5930
5931 // Check whether the type matches the abstract type.
5932 QualType T = TL.getType();
5933 if (T->isArrayType()) {
5935 T = Info.S.Context.getBaseElementType(T);
5936 }
5937 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5938 if (CT != Info.AbstractType) return;
5939
5940 // It matched; do some magic.
5941 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5942 if (Sel == Sema::AbstractArrayType) {
5943 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5944 << T << TL.getSourceRange();
5945 } else {
5946 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5947 << Sel << T << TL.getSourceRange();
5948 }
5949 Info.DiagnoseAbstractType();
5950 }
5951};
5952
5953void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5955 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5956}
5957
5958}
5959
5960/// Check for invalid uses of an abstract type in a function declaration.
5961static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5962 FunctionDecl *FD) {
5963 // No need to do the check on definitions, which require that
5964 // the return/param types be complete.
5966 return;
5967
5968 // For safety's sake, just ignore it if we don't have type source
5969 // information. This should never happen for non-implicit methods,
5970 // but...
5971 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5972 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5973}
5974
5975/// Check for invalid uses of an abstract type in a variable0 declaration.
5976static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5977 VarDecl *VD) {
5978 // No need to do the check on definitions, which require that
5979 // the type is complete.
5981 return;
5982
5983 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5985}
5986
5987/// Check for invalid uses of an abstract type within a class definition.
5988static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5989 CXXRecordDecl *RD) {
5990 for (auto *D : RD->decls()) {
5991 if (D->isImplicit()) continue;
5992
5993 // Step through friends to the befriended declaration.
5994 if (auto *FD = dyn_cast<FriendDecl>(D)) {
5995 D = FD->getFriendDecl();
5996 if (!D) continue;
5997 }
5998
5999 // Functions and function templates.
6000 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6001 CheckAbstractClassUsage(Info, FD);
6002 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6003 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6004
6005 // Fields and static variables.
6006 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6007 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6008 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6009 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6010 CheckAbstractClassUsage(Info, VD);
6011 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6012 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6013
6014 // Nested classes and class templates.
6015 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6016 CheckAbstractClassUsage(Info, RD);
6017 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6018 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6019 }
6020 }
6021}
6022
6024 Attr *ClassAttr = getDLLAttr(Class);
6025 if (!ClassAttr)
6026 return;
6027
6028 assert(ClassAttr->getKind() == attr::DLLExport);
6029
6030 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6031
6033 // Don't go any further if this is just an explicit instantiation
6034 // declaration.
6035 return;
6036
6037 // Add a context note to explain how we got to any diagnostics produced below.
6038 struct MarkingClassDllexported {
6039 Sema &S;
6040 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6041 SourceLocation AttrLoc)
6042 : S(S) {
6045 Ctx.PointOfInstantiation = AttrLoc;
6046 Ctx.Entity = Class;
6048 }
6049 ~MarkingClassDllexported() {
6051 }
6052 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6053
6054 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6055 S.MarkVTableUsed(Class->getLocation(), Class, true);
6056
6057 for (Decl *Member : Class->decls()) {
6058 // Skip members that were not marked exported.
6059 if (!Member->hasAttr<DLLExportAttr>())
6060 continue;
6061
6062 // Defined static variables that are members of an exported base
6063 // class must be marked export too.
6064 auto *VD = dyn_cast<VarDecl>(Member);
6065 if (VD && VD->getStorageClass() == SC_Static &&
6067 S.MarkVariableReferenced(VD->getLocation(), VD);
6068
6069 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6070 if (!MD)
6071 continue;
6072
6073 if (MD->isUserProvided()) {
6074 // Instantiate non-default class member functions ...
6075
6076 // .. except for certain kinds of template specializations.
6077 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6078 continue;
6079
6080 // If this is an MS ABI dllexport default constructor, instantiate any
6081 // default arguments.
6083 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6084 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6086 }
6087 }
6088
6089 S.MarkFunctionReferenced(Class->getLocation(), MD);
6090
6091 // The function will be passed to the consumer when its definition is
6092 // encountered.
6093 } else if (MD->isExplicitlyDefaulted()) {
6094 // Synthesize and instantiate explicitly defaulted methods.
6095 S.MarkFunctionReferenced(Class->getLocation(), MD);
6096
6098 // Except for explicit instantiation defs, we will not see the
6099 // definition again later, so pass it to the consumer now.
6101 }
6102 } else if (!MD->isTrivial() ||
6103 MD->isCopyAssignmentOperator() ||
6104 MD->isMoveAssignmentOperator()) {
6105 // Synthesize and instantiate non-trivial implicit methods, and the copy
6106 // and move assignment operators. The latter are exported even if they
6107 // are trivial, because the address of an operator can be taken and
6108 // should compare equal across libraries.
6109 S.MarkFunctionReferenced(Class->getLocation(), MD);
6110
6111 // There is no later point when we will see the definition of this
6112 // function, so pass it to the consumer now.
6114 }
6115 }
6116}
6117
6119 CXXRecordDecl *Class) {
6120 // Only the MS ABI has default constructor closures, so we don't need to do
6121 // this semantic checking anywhere else.
6123 return;
6124
6125 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6126 for (Decl *Member : Class->decls()) {
6127 // Look for exported default constructors.
6128 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6129 if (!CD || !CD->isDefaultConstructor())
6130 continue;
6131 auto *Attr = CD->getAttr<DLLExportAttr>();
6132 if (!Attr)
6133 continue;
6134
6135 // If the class is non-dependent, mark the default arguments as ODR-used so
6136 // that we can properly codegen the constructor closure.
6137 if (!Class->isDependentContext()) {
6138 for (ParmVarDecl *PD : CD->parameters()) {
6139 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6141 }
6142 }
6143
6144 if (LastExportedDefaultCtor) {
6145 S.Diag(LastExportedDefaultCtor->getLocation(),
6146 diag::err_attribute_dll_ambiguous_default_ctor)
6147 << Class;
6148 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6149 << CD->getDeclName();
6150 return;
6151 }
6152 LastExportedDefaultCtor = CD;
6153 }
6154}
6155
6157 CXXRecordDecl *Class) {
6158 bool ErrorReported = false;
6159 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6160 ClassTemplateDecl *TD) {
6161 if (ErrorReported)
6162 return;
6163 S.Diag(TD->getLocation(),
6164 diag::err_cuda_device_builtin_surftex_cls_template)
6165 << /*surface*/ 0 << TD;
6166 ErrorReported = true;
6167 };
6168
6169 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6170 if (!TD) {
6171 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6172 if (!SD) {
6173 S.Diag(Class->getLocation(),
6174 diag::err_cuda_device_builtin_surftex_ref_decl)
6175 << /*surface*/ 0 << Class;
6176 S.Diag(Class->getLocation(),
6177 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6178 << Class;
6179 return;
6180 }
6181 TD = SD->getSpecializedTemplate();
6182 }
6183
6185 unsigned N = Params->size();
6186
6187 if (N != 2) {
6188 reportIllegalClassTemplate(S, TD);
6189 S.Diag(TD->getLocation(),
6190 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6191 << TD << 2;
6192 }
6193 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6194 reportIllegalClassTemplate(S, TD);
6195 S.Diag(TD->getLocation(),
6196 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6197 << TD << /*1st*/ 0 << /*type*/ 0;
6198 }
6199 if (N > 1) {
6200 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6201 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6202 reportIllegalClassTemplate(S, TD);
6203 S.Diag(TD->getLocation(),
6204 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6205 << TD << /*2nd*/ 1 << /*integer*/ 1;
6206 }
6207 }
6208}
6209
6211 CXXRecordDecl *Class) {
6212 bool ErrorReported = false;
6213 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6214 ClassTemplateDecl *TD) {
6215 if (ErrorReported)
6216 return;
6217 S.Diag(TD->getLocation(),
6218 diag::err_cuda_device_builtin_surftex_cls_template)
6219 << /*texture*/ 1 << TD;
6220 ErrorReported = true;
6221 };
6222
6223 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6224 if (!TD) {
6225 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6226 if (!SD) {
6227 S.Diag(Class->getLocation(),
6228 diag::err_cuda_device_builtin_surftex_ref_decl)
6229 << /*texture*/ 1 << Class;
6230 S.Diag(Class->getLocation(),
6231 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6232 << Class;
6233 return;
6234 }
6235 TD = SD->getSpecializedTemplate();
6236 }
6237
6239 unsigned N = Params->size();
6240
6241 if (N != 3) {
6242 reportIllegalClassTemplate(S, TD);
6243 S.Diag(TD->getLocation(),
6244 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6245 << TD << 3;
6246 }
6247 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6248 reportIllegalClassTemplate(S, TD);
6249 S.Diag(TD->getLocation(),
6250 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6251 << TD << /*1st*/ 0 << /*type*/ 0;
6252 }
6253 if (N > 1) {
6254 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6255 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6256 reportIllegalClassTemplate(S, TD);
6257 S.Diag(TD->getLocation(),
6258 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6259 << TD << /*2nd*/ 1 << /*integer*/ 1;
6260 }
6261 }
6262 if (N > 2) {
6263 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6264 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6265 reportIllegalClassTemplate(S, TD);
6266 S.Diag(TD->getLocation(),
6267 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6268 << TD << /*3rd*/ 2 << /*integer*/ 1;
6269 }
6270 }
6271}
6272
6274 // Mark any compiler-generated routines with the implicit code_seg attribute.
6275 for (auto *Method : Class->methods()) {
6276 if (Method->isUserProvided())
6277 continue;
6278 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6279 Method->addAttr(A);
6280 }
6281}
6282
6283/// Check class-level dllimport/dllexport attribute.
6285 Attr *ClassAttr = getDLLAttr(Class);
6286
6287 // MSVC inherits DLL attributes to partial class template specializations.
6288 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6289 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6290 if (Attr *TemplateAttr =
6291 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6292 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6293 A->setInherited(true);
6294 ClassAttr = A;
6295 }
6296 }
6297 }
6298
6299 if (!ClassAttr)
6300 return;
6301
6302 if (!Class->isExternallyVisible()) {
6303 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6304 << Class << ClassAttr;
6305 return;
6306 }
6307
6309 !ClassAttr->isInherited()) {
6310 // Diagnose dll attributes on members of class with dll attribute.
6311 for (Decl *Member : Class->decls()) {
6312 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6313 continue;
6314 InheritableAttr *MemberAttr = getDLLAttr(Member);
6315 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6316 continue;
6317
6318 Diag(MemberAttr->getLocation(),
6319 diag::err_attribute_dll_member_of_dll_class)
6320 << MemberAttr << ClassAttr;
6321 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6322 Member->setInvalidDecl();
6323 }
6324 }
6325
6326 if (Class->getDescribedClassTemplate())
6327 // Don't inherit dll attribute until the template is instantiated.
6328 return;
6329
6330 // The class is either imported or exported.
6331 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6332
6333 // Check if this was a dllimport attribute propagated from a derived class to
6334 // a base class template specialization. We don't apply these attributes to
6335 // static data members.
6336 const bool PropagatedImport =
6337 !ClassExported &&
6338 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6339
6340 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6341
6342 // Ignore explicit dllexport on explicit class template instantiation
6343 // declarations, except in MinGW mode.
6344 if (ClassExported && !ClassAttr->isInherited() &&
6346 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6347 Class->dropAttr<DLLExportAttr>();
6348 return;
6349 }
6350
6351 // Force declaration of implicit members so they can inherit the attribute.
6352 ForceDeclarationOfImplicitMembers(Class);
6353
6354 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6355 // seem to be true in practice?
6356
6357 for (Decl *Member : Class->decls()) {
6358 VarDecl *VD = dyn_cast<VarDecl>(Member);
6359 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6360
6361 // Only methods and static fields inherit the attributes.
6362 if (!VD && !MD)
6363 continue;
6364
6365 if (MD) {
6366 // Don't process deleted methods.
6367 if (MD->isDeleted())
6368 continue;
6369
6370 if (MD->isInlined()) {
6371 // MinGW does not import or export inline methods. But do it for
6372 // template instantiations.
6376 continue;
6377
6378 // MSVC versions before 2015 don't export the move assignment operators
6379 // and move constructor, so don't attempt to import/export them if
6380 // we have a definition.
6381 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6382 if ((MD->isMoveAssignmentOperator() ||
6383 (Ctor && Ctor->isMoveConstructor())) &&
6384 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6385 continue;
6386
6387 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6388 // operator is exported anyway.
6389 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6390 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6391 continue;
6392 }
6393 }
6394
6395 // Don't apply dllimport attributes to static data members of class template
6396 // instantiations when the attribute is propagated from a derived class.
6397 if (VD && PropagatedImport)
6398 continue;
6399
6400 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6401 continue;
6402
6403 if (!getDLLAttr(Member)) {
6404 InheritableAttr *NewAttr = nullptr;
6405
6406 // Do not export/import inline function when -fno-dllexport-inlines is
6407 // passed. But add attribute for later local static var check.
6408 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6411 if (ClassExported) {
6412 NewAttr = ::new (getASTContext())
6413 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6414 } else {
6415 NewAttr = ::new (getASTContext())
6416 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6417 }
6418 } else {
6419 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6420 }
6421
6422 NewAttr->setInherited(true);
6423 Member->addAttr(NewAttr);
6424
6425 if (MD) {
6426 // Propagate DLLAttr to friend re-declarations of MD that have already
6427 // been constructed.
6428 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6429 FD = FD->getPreviousDecl()) {
6431 continue;
6432 assert(!getDLLAttr(FD) &&
6433 "friend re-decl should not already have a DLLAttr");
6434 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6435 NewAttr->setInherited(true);
6436 FD->addAttr(NewAttr);
6437 }
6438 }
6439 }
6440 }
6441
6442 if (ClassExported)
6443 DelayedDllExportClasses.push_back(Class);
6444}
6445
6446/// Perform propagation of DLL attributes from a derived class to a
6447/// templated base class for MS compatibility.
6449 CXXRecordDecl *Class, Attr *ClassAttr,
6450 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6451 if (getDLLAttr(
6452 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6453 // If the base class template has a DLL attribute, don't try to change it.
6454 return;
6455 }
6456
6457 auto TSK = BaseTemplateSpec->getSpecializationKind();
6458 if (!getDLLAttr(BaseTemplateSpec) &&
6460 TSK == TSK_ImplicitInstantiation)) {
6461 // The template hasn't been instantiated yet (or it has, but only as an
6462 // explicit instantiation declaration or implicit instantiation, which means
6463 // we haven't codegenned any members yet), so propagate the attribute.
6464 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6465 NewAttr->setInherited(true);
6466 BaseTemplateSpec->addAttr(NewAttr);
6467
6468 // If this was an import, mark that we propagated it from a derived class to
6469 // a base class template specialization.
6470 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6471 ImportAttr->setPropagatedToBaseTemplate();
6472
6473 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6474 // needs to be run again to work see the new attribute. Otherwise this will
6475 // get run whenever the template is instantiated.
6476 if (TSK != TSK_Undeclared)
6477 checkClassLevelDLLAttribute(BaseTemplateSpec);
6478
6479 return;
6480 }
6481
6482 if (getDLLAttr(BaseTemplateSpec)) {
6483 // The template has already been specialized or instantiated with an
6484 // attribute, explicitly or through propagation. We should not try to change
6485 // it.
6486 return;
6487 }
6488
6489 // The template was previously instantiated or explicitly specialized without
6490 // a dll attribute, It's too late for us to add an attribute, so warn that
6491 // this is unsupported.
6492 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6493 << BaseTemplateSpec->isExplicitSpecialization();
6494 Diag(ClassAttr->getLocation(), diag::note_attribute);
6495 if (BaseTemplateSpec->isExplicitSpecialization()) {
6496 Diag(BaseTemplateSpec->getLocation(),
6497 diag::note_template_class_explicit_specialization_was_here)
6498 << BaseTemplateSpec;
6499 } else {
6500 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6501 diag::note_template_class_instantiation_was_here)
6502 << BaseTemplateSpec;
6503 }
6504}
6505
6506/// Determine the kind of defaulting that would be done for a given function.
6507///
6508/// If the function is both a default constructor and a copy / move constructor
6509/// (due to having a default argument for the first parameter), this picks
6510/// CXXDefaultConstructor.
6511///
6512/// FIXME: Check that case is properly handled by all callers.
6515 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6516 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6517 if (Ctor->isDefaultConstructor())
6519
6520 if (Ctor->isCopyConstructor())
6522
6523 if (Ctor->isMoveConstructor())
6525 }
6526
6527 if (MD->isCopyAssignmentOperator())
6529
6530 if (MD->isMoveAssignmentOperator())
6532
6533 if (isa<CXXDestructorDecl>(FD))
6534 return Sema::CXXDestructor;
6535 }
6536
6537 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6538 case OO_EqualEqual:
6539 return DefaultedComparisonKind::Equal;
6540
6541 case OO_ExclaimEqual:
6542 return DefaultedComparisonKind::NotEqual;
6543
6544 case OO_Spaceship:
6545 // No point allowing this if <=> doesn't exist in the current language mode.
6546 if (!getLangOpts().CPlusPlus20)
6547 break;
6548 return DefaultedComparisonKind::ThreeWay;
6549
6550 case OO_Less:
6551 case OO_LessEqual:
6552 case OO_Greater:
6553 case OO_GreaterEqual:
6554 // No point allowing this if <=> doesn't exist in the current language mode.
6555 if (!getLangOpts().CPlusPlus20)
6556 break;
6557 return DefaultedComparisonKind::Relational;
6558
6559 default:
6560 break;
6561 }
6562
6563 // Not defaultable.
6564 return DefaultedFunctionKind();
6565}
6566
6568 SourceLocation DefaultLoc) {
6570 if (DFK.isComparison())
6571 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6572
6573 switch (DFK.asSpecialMember()) {
6576 cast<CXXConstructorDecl>(FD));
6577 break;
6579 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6580 break;
6582 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6583 break;
6585 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6586 break;
6588 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6589 break;
6591 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6592 break;
6593 case Sema::CXXInvalid:
6594 llvm_unreachable("Invalid special member.");
6595 }
6596}
6597
6598/// Determine whether a type is permitted to be passed or returned in
6599/// registers, per C++ [class.temporary]p3.
6602 if (D->isDependentType() || D->isInvalidDecl())
6603 return false;
6604
6605 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6606 // The PS4 platform ABI follows the behavior of Clang 3.2.
6608 return !D->hasNonTrivialDestructorForCall() &&
6610
6611 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6612 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6613 bool DtorIsTrivialForCall = false;
6614
6615 // If a class has at least one non-deleted, trivial copy constructor, it
6616 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6617 //
6618 // Note: This permits classes with non-trivial copy or move ctors to be
6619 // passed in registers, so long as they *also* have a trivial copy ctor,
6620 // which is non-conforming.
6624 CopyCtorIsTrivial = true;
6626 CopyCtorIsTrivialForCall = true;
6627 }
6628 } else {
6629 for (const CXXConstructorDecl *CD : D->ctors()) {
6630 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6631 if (CD->isTrivial())
6632 CopyCtorIsTrivial = true;
6633 if (CD->isTrivialForCall())
6634 CopyCtorIsTrivialForCall = true;
6635 }
6636 }
6637 }
6638
6639 if (D->needsImplicitDestructor()) {
6640 if (!D->defaultedDestructorIsDeleted() &&
6642 DtorIsTrivialForCall = true;
6643 } else if (const auto *DD = D->getDestructor()) {
6644 if (!DD->isDeleted() && DD->isTrivialForCall())
6645 DtorIsTrivialForCall = true;
6646 }
6647
6648 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6649 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6650 return true;
6651
6652 // If a class has a destructor, we'd really like to pass it indirectly
6653 // because it allows us to elide copies. Unfortunately, MSVC makes that
6654 // impossible for small types, which it will pass in a single register or
6655 // stack slot. Most objects with dtors are large-ish, so handle that early.
6656 // We can't call out all large objects as being indirect because there are
6657 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6658 // how we pass large POD types.
6659
6660 // Note: This permits small classes with nontrivial destructors to be
6661 // passed in registers, which is non-conforming.
6662 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6663 uint64_t TypeSize = isAArch64 ? 128 : 64;
6664
6665 if (CopyCtorIsTrivial &&
6666 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6667 return true;
6668 return false;
6669 }
6670
6671 // Per C++ [class.temporary]p3, the relevant condition is:
6672 // each copy constructor, move constructor, and destructor of X is
6673 // either trivial or deleted, and X has at least one non-deleted copy
6674 // or move constructor
6675 bool HasNonDeletedCopyOrMove = false;
6676
6680 return false;
6681 HasNonDeletedCopyOrMove = true;
6682 }
6683
6684 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6687 return false;
6688 HasNonDeletedCopyOrMove = true;
6689 }
6690
6693 return false;
6694
6695 for (const CXXMethodDecl *MD : D->methods()) {
6696 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6697 continue;
6698
6699 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6700 if (CD && CD->isCopyOrMoveConstructor())
6701 HasNonDeletedCopyOrMove = true;
6702 else if (!isa<CXXDestructorDecl>(MD))
6703 continue;
6704
6705 if (!MD->isTrivialForCall())
6706 return false;
6707 }
6708
6709 return HasNonDeletedCopyOrMove;
6710}
6711
6712/// Report an error regarding overriding, along with any relevant
6713/// overridden methods.
6714///
6715/// \param DiagID the primary error to report.
6716/// \param MD the overriding method.
6717static bool
6718ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6719 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6720 bool IssuedDiagnostic = false;
6721 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6722 if (Report(O)) {
6723 if (!IssuedDiagnostic) {
6724 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6725 IssuedDiagnostic = true;
6726 }
6727 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6728 }
6729 }
6730 return IssuedDiagnostic;
6731}
6732
6733/// Perform semantic checks on a class definition that has been
6734/// completing, introducing implicitly-declared members, checking for
6735/// abstract types, etc.
6736///
6737/// \param S The scope in which the class was parsed. Null if we didn't just
6738/// parse a class definition.
6739/// \param Record The completed class.
6741 if (!Record)
6742 return;
6743
6744 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6745 AbstractUsageInfo Info(*this, Record);
6746 CheckAbstractClassUsage(Info, Record);
6747 }
6748
6749 // If this is not an aggregate type and has no user-declared constructor,
6750 // complain about any non-static data members of reference or const scalar
6751 // type, since they will never get initializers.
6752 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6753 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6754 !Record->isLambda()) {
6755 bool Complained = false;
6756 for (const auto *F : Record->fields()) {
6757 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6758 continue;
6759
6760 if (F->getType()->isReferenceType() ||
6761 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6762 if (!Complained) {
6763 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6764 << Record->getTagKind() << Record;
6765 Complained = true;
6766 }
6767
6768 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6769 << F->getType()->isReferenceType()
6770 << F->getDeclName();
6771 }
6772 }
6773 }
6774
6775 if (Record->getIdentifier()) {
6776 // C++ [class.mem]p13:
6777 // If T is the name of a class, then each of the following shall have a
6778 // name different from T:
6779 // - every member of every anonymous union that is a member of class T.
6780 //
6781 // C++ [class.mem]p14:
6782 // In addition, if class T has a user-declared constructor (12.1), every
6783 // non-static data member of class T shall have a name different from T.
6784 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6785 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6786 ++I) {
6787 NamedDecl *D = (*I)->getUnderlyingDecl();
6788 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6789 Record->hasUserDeclaredConstructor()) ||
6790 isa<IndirectFieldDecl>(D)) {
6791 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6792 << D->getDeclName();
6793 break;
6794 }
6795 }
6796 }
6797
6798 // Warn if the class has virtual methods but non-virtual public destructor.
6799 if (Record->isPolymorphic() && !Record->isDependentType()) {
6800 CXXDestructorDecl *dtor = Record->getDestructor();
6801 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6802 !Record->hasAttr<FinalAttr>())
6803 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6804 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6805 }
6806
6807 if (Record->isAbstract()) {
6808 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6809 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6810 << FA->isSpelledAsSealed();
6811 DiagnoseAbstractType(Record);
6812 }
6813 }
6814
6815 // Warn if the class has a final destructor but is not itself marked final.
6816 if (!Record->hasAttr<FinalAttr>()) {
6817 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6818 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6819 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6820 << FA->isSpelledAsSealed()
6822 getLocForEndOfToken(Record->getLocation()),
6823 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6824 Diag(Record->getLocation(),
6825 diag::note_final_dtor_non_final_class_silence)
6826 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6827 }
6828 }
6829 }
6830
6831 // See if trivial_abi has to be dropped.
6832 if (Record->hasAttr<TrivialABIAttr>())
6833 checkIllFormedTrivialABIStruct(*Record);
6834
6835 // Set HasTrivialSpecialMemberForCall if the record has attribute
6836 // "trivial_abi".
6837 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6838
6839 if (HasTrivialABI)
6840 Record->setHasTrivialSpecialMemberForCall();
6841
6842 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6843 // We check these last because they can depend on the properties of the
6844 // primary comparison functions (==, <=>).
6845 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6846
6847 // Perform checks that can't be done until we know all the properties of a
6848 // member function (whether it's defaulted, deleted, virtual, overriding,
6849 // ...).
6850 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6851 // A static function cannot override anything.
6852 if (MD->getStorageClass() == SC_Static) {
6853 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6854 [](const CXXMethodDecl *) { return true; }))
6855 return;
6856 }
6857
6858 // A deleted function cannot override a non-deleted function and vice
6859 // versa.
6860 if (ReportOverrides(*this,
6861 MD->isDeleted() ? diag::err_deleted_override
6862 : diag::err_non_deleted_override,
6863 MD, [&](const CXXMethodDecl *V) {
6864 return MD->isDeleted() != V->isDeleted();
6865 })) {
6866 if (MD->isDefaulted() && MD->isDeleted())
6867 // Explain why this defaulted function was deleted.
6868 DiagnoseDeletedDefaultedFunction(MD);
6869 return;
6870 }
6871
6872 // A consteval function cannot override a non-consteval function and vice
6873 // versa.
6874 if (ReportOverrides(*this,
6875 MD->isConsteval() ? diag::err_consteval_override
6876 : diag::err_non_consteval_override,
6877 MD, [&](const CXXMethodDecl *V) {
6878 return MD->isConsteval() != V->isConsteval();
6879 })) {
6880 if (MD->isDefaulted() && MD->isDeleted())
6881 // Explain why this defaulted function was deleted.
6882 DiagnoseDeletedDefaultedFunction(MD);
6883 return;
6884 }
6885 };
6886
6887 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6888 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6889 return false;
6890
6891 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6892 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6893 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6894 DefaultedSecondaryComparisons.push_back(FD);
6895 return true;
6896 }
6897
6898 CheckExplicitlyDefaultedFunction(S, FD);
6899 return false;
6900 };
6901
6902 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6903 // Check whether the explicitly-defaulted members are valid.
6904 bool Incomplete = CheckForDefaultedFunction(M);
6905
6906 // Skip the rest of the checks for a member of a dependent class.
6907 if (Record->isDependentType())
6908 return;
6909
6910 // For an explicitly defaulted or deleted special member, we defer
6911 // determining triviality until the class is complete. That time is now!
6912 CXXSpecialMember CSM = getSpecialMember(M);
6913 if (!M->isImplicit() && !M->isUserProvided()) {
6914 if (CSM != CXXInvalid) {
6915 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6916 // Inform the class that we've finished declaring this member.
6917 Record->finishedDefaultedOrDeletedMember(M);
6918 M->setTrivialForCall(
6919 HasTrivialABI ||
6920 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6921 Record->setTrivialForCallFlags(M);
6922 }
6923 }
6924
6925 // Set triviality for the purpose of calls if this is a user-provided
6926 // copy/move constructor or destructor.
6927 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6928 CSM == CXXDestructor) && M->isUserProvided()) {
6929 M->setTrivialForCall(HasTrivialABI);
6930 Record->setTrivialForCallFlags(M);
6931 }
6932
6933 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6934 M->hasAttr<DLLExportAttr>()) {
6935 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6936 M->isTrivial() &&
6937 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6938 CSM == CXXDestructor))
6939 M->dropAttr<DLLExportAttr>();
6940
6941 if (M->hasAttr<DLLExportAttr>()) {
6942 // Define after any fields with in-class initializers have been parsed.
6943 DelayedDllExportMemberFunctions.push_back(M);
6944 }
6945 }
6946
6947 // Define defaulted constexpr virtual functions that override a base class
6948 // function right away.
6949 // FIXME: We can defer doing this until the vtable is marked as used.
6950 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6951 DefineDefaultedFunction(*this, M, M->getLocation());
6952
6953 if (!Incomplete)
6954 CheckCompletedMemberFunction(M);
6955 };
6956
6957 // Check the destructor before any other member function. We need to
6958 // determine whether it's trivial in order to determine whether the claas
6959 // type is a literal type, which is a prerequisite for determining whether
6960 // other special member functions are valid and whether they're implicitly
6961 // 'constexpr'.
6962 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6963 CompleteMemberFunction(Dtor);
6964
6965 bool HasMethodWithOverrideControl = false,
6966 HasOverridingMethodWithoutOverrideControl = false;
6967 for (auto *D : Record->decls()) {
6968 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6969 // FIXME: We could do this check for dependent types with non-dependent
6970 // bases.
6971 if (!Record->isDependentType()) {
6972 // See if a method overloads virtual methods in a base
6973 // class without overriding any.
6974 if (!M->isStatic())
6975 DiagnoseHiddenVirtualMethods(M);
6976 if (M->hasAttr<OverrideAttr>())
6977 HasMethodWithOverrideControl = true;
6978 else if (M->size_overridden_methods() > 0)
6979 HasOverridingMethodWithoutOverrideControl = true;
6980 }
6981
6982 if (!isa<CXXDestructorDecl>(M))
6983 CompleteMemberFunction(M);
6984 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6985 CheckForDefaultedFunction(
6986 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6987 }
6988 }
6989
6990 if (HasOverridingMethodWithoutOverrideControl) {
6991 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6992 for (auto *M : Record->methods())
6993 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6994 }
6995
6996 // Check the defaulted secondary comparisons after any other member functions.
6997 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6998 CheckExplicitlyDefaultedFunction(S, FD);
6999
7000 // If this is a member function, we deferred checking it until now.
7001 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7002 CheckCompletedMemberFunction(MD);
7003 }
7004
7005 // ms_struct is a request to use the same ABI rules as MSVC. Check
7006 // whether this class uses any C++ features that are implemented
7007 // completely differently in MSVC, and if so, emit a diagnostic.
7008 // That diagnostic defaults to an error, but we allow projects to
7009 // map it down to a warning (or ignore it). It's a fairly common
7010 // practice among users of the ms_struct pragma to mass-annotate
7011 // headers, sweeping up a bunch of types that the project doesn't
7012 // really rely on MSVC-compatible layout for. We must therefore
7013 // support "ms_struct except for C++ stuff" as a secondary ABI.
7014 // Don't emit this diagnostic if the feature was enabled as a
7015 // language option (as opposed to via a pragma or attribute), as
7016 // the option -mms-bitfields otherwise essentially makes it impossible
7017 // to build C++ code, unless this diagnostic is turned off.
7018 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7019 (Record->isPolymorphic() || Record->getNumBases())) {
7020 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7021 }
7022
7023 checkClassLevelDLLAttribute(Record);
7024 checkClassLevelCodeSegAttribute(Record);
7025
7026 bool ClangABICompat4 =
7027 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7029 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7030 bool CanPass = canPassInRegisters(*this, Record, CCK);
7031
7032 // Do not change ArgPassingRestrictions if it has already been set to
7033 // APK_CanNeverPassInRegs.
7034 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7035 Record->setArgPassingRestrictions(CanPass
7038
7039 // If canPassInRegisters returns true despite the record having a non-trivial
7040 // destructor, the record is destructed in the callee. This happens only when
7041 // the record or one of its subobjects has a field annotated with trivial_abi
7042 // or a field qualified with ObjC __strong/__weak.
7044 Record->setParamDestroyedInCallee(true);
7045 else if (Record->hasNonTrivialDestructor())
7046 Record->setParamDestroyedInCallee(CanPass);
7047
7048 if (getLangOpts().ForceEmitVTables) {
7049 // If we want to emit all the vtables, we need to mark it as used. This
7050 // is especially required for cases like vtable assumption loads.
7051 MarkVTableUsed(Record->getInnerLocStart(), Record);
7052 }
7053
7054 if (getLangOpts().CUDA) {
7055 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7057 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7059 }
7060}
7061
7062/// Look up the special member function that would be called by a special
7063/// member function for a subobject of class type.
7064///
7065/// \param Class The class type of the subobject.
7066/// \param CSM The kind of special member function.
7067/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7068/// \param ConstRHS True if this is a copy operation with a const object
7069/// on its RHS, that is, if the argument to the outer special member
7070/// function is 'const' and this is not a field marked 'mutable'.
7073 unsigned FieldQuals, bool ConstRHS) {
7074 unsigned LHSQuals = 0;
7076 LHSQuals = FieldQuals;
7077
7078 unsigned RHSQuals = FieldQuals;
7080 RHSQuals = 0;
7081 else if (ConstRHS)
7082 RHSQuals |= Qualifiers::Const;
7083
7084 return S.LookupSpecialMember(Class, CSM,
7085 RHSQuals & Qualifiers::Const,
7086 RHSQuals & Qualifiers::Volatile,
7087 false,
7088 LHSQuals & Qualifiers::Const,
7089 LHSQuals & Qualifiers::Volatile);
7090}
7091
7093 Sema &S;
7094 SourceLocation UseLoc;
7095
7096 /// A mapping from the base classes through which the constructor was
7097 /// inherited to the using shadow declaration in that base class (or a null
7098 /// pointer if the constructor was declared in that base class).
7099 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7100 InheritedFromBases;
7101
7102public:
7105 : S(S), UseLoc(UseLoc) {
7106 bool DiagnosedMultipleConstructedBases = false;
7107 CXXRecordDecl *ConstructedBase = nullptr;
7108 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7109
7110 // Find the set of such base class subobjects and check that there's a
7111 // unique constructed subobject.
7112 for (auto *D : Shadow->redecls()) {
7113 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7114 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7115 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7116
7117 InheritedFromBases.insert(
7118 std::make_pair(DNominatedBase->getCanonicalDecl(),
7119 DShadow->getNominatedBaseClassShadowDecl()));
7120 if (DShadow->constructsVirtualBase())
7121 InheritedFromBases.insert(
7122 std::make_pair(DConstructedBase->getCanonicalDecl(),
7123 DShadow->getConstructedBaseClassShadowDecl()));
7124 else
7125 assert(DNominatedBase == DConstructedBase);
7126
7127 // [class.inhctor.init]p2:
7128 // If the constructor was inherited from multiple base class subobjects
7129 // of type B, the program is ill-formed.
7130 if (!ConstructedBase) {
7131 ConstructedBase = DConstructedBase;
7132 ConstructedBaseIntroducer = D->getIntroducer();
7133 } else if (ConstructedBase != DConstructedBase &&
7134 !Shadow->isInvalidDecl()) {
7135 if (!DiagnosedMultipleConstructedBases) {
7136 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7137 << Shadow->getTargetDecl();
7138 S.Diag(ConstructedBaseIntroducer->getLocation(),
7139 diag::note_ambiguous_inherited_constructor_using)
7140 << ConstructedBase;
7141 DiagnosedMultipleConstructedBases = true;
7142 }
7143 S.Diag(D->getIntroducer()->getLocation(),
7144 diag::note_ambiguous_inherited_constructor_using)
7145 << DConstructedBase;
7146 }
7147 }
7148
7149 if (DiagnosedMultipleConstructedBases)
7150 Shadow->setInvalidDecl();
7151 }
7152
7153 /// Find the constructor to use for inherited construction of a base class,
7154 /// and whether that base class constructor inherits the constructor from a
7155 /// virtual base class (in which case it won't actually invoke it).
7156 std::pair<CXXConstructorDecl *, bool>
7158 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7159 if (It == InheritedFromBases.end())
7160 return std::make_pair(nullptr, false);
7161
7162 // This is an intermediary class.
7163 if (It->second)
7164 return std::make_pair(
7165 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7166 It->second->constructsVirtualBase());
7167
7168 // This is the base class from which the constructor was inherited.
7169 return std::make_pair(Ctor, false);
7170 }
7171};
7172
7173/// Is the special member function which would be selected to perform the
7174/// specified operation on the specified class type a constexpr constructor?
7175static bool
7177 Sema::CXXSpecialMember CSM, unsigned Quals,
7178 bool ConstRHS,
7179 CXXConstructorDecl *InheritedCtor = nullptr,
7180 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7181 // If we're inheriting a constructor, see if we need to call it for this base
7182 // class.
7183 if (InheritedCtor) {
7184 assert(CSM == Sema::CXXDefaultConstructor);
7185 auto BaseCtor =
7186 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7187 if (BaseCtor)
7188 return BaseCtor->isConstexpr();
7189 }
7190
7191 if (CSM == Sema::CXXDefaultConstructor)
7192 return ClassDecl->hasConstexprDefaultConstructor();
7193 if (CSM == Sema::CXXDestructor)
7194 return ClassDecl->hasConstexprDestructor();
7195
7197 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7198 if (!SMOR.getMethod())
7199 // A constructor we wouldn't select can't be "involved in initializing"
7200 // anything.
7201 return true;
7202 return SMOR.getMethod()->isConstexpr();
7203}
7204
7205/// Determine whether the specified special member function would be constexpr
7206/// if it were implicitly defined.
7208 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7209 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7210 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7211 if (!S.getLangOpts().CPlusPlus11)
7212 return false;
7213
7214 // C++11 [dcl.constexpr]p4:
7215 // In the definition of a constexpr constructor [...]
7216 bool Ctor = true;
7217 switch (CSM) {
7219 if (Inherited)
7220 break;
7221 // Since default constructor lookup is essentially trivial (and cannot
7222 // involve, for instance, template instantiation), we compute whether a
7223 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7224 //
7225 // This is important for performance; we need to know whether the default
7226 // constructor is constexpr to determine whether the type is a literal type.
7227 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7228
7231 // For copy or move constructors, we need to perform overload resolution.
7232 break;
7233
7236 if (!S.getLangOpts().CPlusPlus14)
7237 return false;
7238 // In C++1y, we need to perform overload resolution.
7239 Ctor = false;
7240 break;
7241
7243 return ClassDecl->defaultedDestructorIsConstexpr();
7244
7245 case Sema::CXXInvalid:
7246 return false;
7247 }
7248
7249 // -- if the class is a non-empty union, or for each non-empty anonymous
7250 // union member of a non-union class, exactly one non-static data member
7251 // shall be initialized; [DR1359]
7252 //
7253 // If we squint, this is guaranteed, since exactly one non-static data member
7254 // will be initialized (if the constructor isn't deleted), we just don't know
7255 // which one.
7256 if (Ctor && ClassDecl->isUnion())
7257 return CSM == Sema::CXXDefaultConstructor
7258 ? ClassDecl->hasInClassInitializer() ||
7259 !ClassDecl->hasVariantMembers()
7260 : true;
7261
7262 // -- the class shall not have any virtual base classes;
7263 if (Ctor && ClassDecl->getNumVBases())
7264 return false;
7265
7266 // C++1y [class.copy]p26:
7267 // -- [the class] is a literal type, and
7268 if (!Ctor && !ClassDecl->isLiteral())
7269 return false;
7270
7271 // -- every constructor involved in initializing [...] base class
7272 // sub-objects shall be a constexpr constructor;
7273 // -- the assignment operator selected to copy/move each direct base
7274 // class is a constexpr function, and
7275 for (const auto &B : ClassDecl->bases()) {
7276 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7277 if (!BaseType) continue;
7278
7279 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7280 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7281 InheritedCtor, Inherited))
7282 return false;
7283 }
7284
7285 // -- every constructor involved in initializing non-static data members
7286 // [...] shall be a constexpr constructor;
7287 // -- every non-static data member and base class sub-object shall be
7288 // initialized
7289 // -- for each non-static data member of X that is of class type (or array
7290 // thereof), the assignment operator selected to copy/move that member is
7291 // a constexpr function
7292 for (const auto *F : ClassDecl->fields()) {
7293 if (F->isInvalidDecl())
7294 continue;
7295 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7296 continue;
7297 QualType BaseType = S.Context.getBaseElementType(F->getType());
7298 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7299 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7300 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7301 BaseType.getCVRQualifiers(),
7302 ConstArg && !F->isMutable()))
7303 return false;
7304 } else if (CSM == Sema::CXXDefaultConstructor) {
7305 return false;
7306 }
7307 }
7308
7309 // All OK, it's constexpr!
7310 return true;
7311}
7312
7313namespace {
7314/// RAII object to register a defaulted function as having its exception
7315/// specification computed.
7316struct ComputingExceptionSpec {
7317 Sema &S;
7318
7319 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7320 : S(S) {
7323 Ctx.PointOfInstantiation = Loc;
7324 Ctx.Entity = FD;
7326 }
7327 ~ComputingExceptionSpec() {
7329 }
7330};
7331}
7332
7337
7340 FunctionDecl *FD,
7342
7345 auto DFK = S.getDefaultedFunctionKind(FD);
7346 if (DFK.isSpecialMember())
7348 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7349 if (DFK.isComparison())
7351 DFK.asComparison());
7352
7353 auto *CD = cast<CXXConstructorDecl>(FD);
7354 assert(CD->getInheritedConstructor() &&
7355 "only defaulted functions and inherited constructors have implicit "
7356 "exception specs");
7358 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7360 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7361}
7362
7364 CXXMethodDecl *MD) {
7366
7367 // Build an exception specification pointing back at this member.
7369 EPI.ExceptionSpec.SourceDecl = MD;
7370
7371 // Set the calling convention to the default for C++ instance methods.
7373 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7374 /*IsCXXMethod=*/true));
7375 return EPI;
7376}
7377
7379 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7381 return;
7382
7383 // Evaluate the exception specification.
7384 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7385 auto ESI = IES.getExceptionSpec();
7386
7387 // Update the type of the special member to use it.
7388 UpdateExceptionSpec(FD, ESI);
7389}
7390
7392 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7393
7394 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7395 if (!DefKind) {
7396 assert(FD->getDeclContext()->isDependentContext());
7397 return;
7398 }
7399
7400 if (DefKind.isComparison())
7401 UnusedPrivateFields.clear();
7402
7403 if (DefKind.isSpecialMember()
7404 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7405 DefKind.asSpecialMember())
7406 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7407 FD->setInvalidDecl();
7408}
7409
7411 CXXSpecialMember CSM) {
7412 CXXRecordDecl *RD = MD->getParent();
7413
7414 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7415 "not an explicitly-defaulted special member");
7416
7417 // Defer all checking for special members of a dependent type.
7418 if (RD->isDependentType())
7419 return false;
7420
7421 // Whether this was the first-declared instance of the constructor.
7422 // This affects whether we implicitly add an exception spec and constexpr.
7423 bool First = MD == MD->getCanonicalDecl();
7424
7425 bool HadError = false;
7426
7427 // C++11 [dcl.fct.def.default]p1:
7428 // A function that is explicitly defaulted shall
7429 // -- be a special member function [...] (checked elsewhere),
7430 // -- have the same type (except for ref-qualifiers, and except that a
7431 // copy operation can take a non-const reference) as an implicit
7432 // declaration, and
7433 // -- not have default arguments.
7434 // C++2a changes the second bullet to instead delete the function if it's
7435 // defaulted on its first declaration, unless it's "an assignment operator,
7436 // and its return type differs or its parameter type is not a reference".
7437 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7438 bool ShouldDeleteForTypeMismatch = false;
7439 unsigned ExpectedParams = 1;
7440 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7441 ExpectedParams = 0;
7442 if (MD->getNumParams() != ExpectedParams) {
7443 // This checks for default arguments: a copy or move constructor with a
7444 // default argument is classified as a default constructor, and assignment
7445 // operations and destructors can't have default arguments.
7446 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7447 << CSM << MD->getSourceRange();
7448 HadError = true;
7449 } else if (MD->isVariadic()) {
7450 if (DeleteOnTypeMismatch)
7451 ShouldDeleteForTypeMismatch = true;
7452 else {
7453 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7454 << CSM << MD->getSourceRange();
7455 HadError = true;
7456 }
7457 }
7458
7460
7461 bool CanHaveConstParam = false;
7462 if (CSM == CXXCopyConstructor)
7463 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7464 else if (CSM == CXXCopyAssignment)
7465 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7466
7467 QualType ReturnType = Context.VoidTy;
7468 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7469 // Check for return type matching.
7470 ReturnType = Type->getReturnType();
7471
7472 QualType DeclType = Context.getTypeDeclType(RD);
7473 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7474 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7475
7476 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7477 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7478 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7479 HadError = true;
7480 }
7481
7482 // A defaulted special member cannot have cv-qualifiers.
7483 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7484 if (DeleteOnTypeMismatch)
7485 ShouldDeleteForTypeMismatch = true;
7486 else {
7487 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7488 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7489 HadError = true;
7490 }
7491 }
7492 }
7493
7494 // Check for parameter type matching.
7495 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7496 bool HasConstParam = false;
7497 if (ExpectedParams && ArgType->isReferenceType()) {
7498 // Argument must be reference to possibly-const T.
7499 QualType ReferentType = ArgType->getPointeeType();
7500 HasConstParam = ReferentType.isConstQualified();
7501
7502 if (ReferentType.isVolatileQualified()) {
7503 if (DeleteOnTypeMismatch)
7504 ShouldDeleteForTypeMismatch = true;
7505 else {
7506 Diag(MD->getLocation(),
7507 diag::err_defaulted_special_member_volatile_param) << CSM;
7508 HadError = true;
7509 }
7510 }
7511
7512 if (HasConstParam && !CanHaveConstParam) {
7513 if (DeleteOnTypeMismatch)
7514 ShouldDeleteForTypeMismatch = true;
7515 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7516 Diag(MD->getLocation(),
7517 diag::err_defaulted_special_member_copy_const_param)
7518 << (CSM == CXXCopyAssignment);
7519 // FIXME: Explain why this special member can't be const.
7520 HadError = true;
7521 } else {
7522 Diag(MD->getLocation(),
7523 diag::err_defaulted_special_member_move_const_param)
7524 << (CSM == CXXMoveAssignment);
7525 HadError = true;
7526 }
7527 }
7528 } else if (ExpectedParams) {
7529 // A copy assignment operator can take its argument by value, but a
7530 // defaulted one cannot.
7531 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7532 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7533 HadError = true;
7534 }
7535
7536 // C++11 [dcl.fct.def.default]p2:
7537 // An explicitly-defaulted function may be declared constexpr only if it
7538 // would have been implicitly declared as constexpr,
7539 // Do not apply this rule to members of class templates, since core issue 1358
7540 // makes such functions always instantiate to constexpr functions. For
7541 // functions which cannot be constexpr (for non-constructors in C++11 and for
7542 // destructors in C++14 and C++17), this is checked elsewhere.
7543 //
7544 // FIXME: This should not apply if the member is deleted.
7545 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7546 HasConstParam);
7547 if ((getLangOpts().CPlusPlus20 ||
7548 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7549 : isa<CXXConstructorDecl>(MD))) &&
7550 MD->isConstexpr() && !Constexpr &&
7552 Diag(MD->getBeginLoc(), MD->isConsteval()
7553 ? diag::err_incorrect_defaulted_consteval
7554 : diag::err_incorrect_defaulted_constexpr)
7555 << CSM;
7556 // FIXME: Explain why the special member can't be constexpr.
7557 HadError = true;
7558 }
7559
7560 if (First) {
7561 // C++2a [dcl.fct.def.default]p3:
7562 // If a function is explicitly defaulted on its first declaration, it is
7563 // implicitly considered to be constexpr if the implicit declaration
7564 // would be.
7566 ? ConstexprSpecKind::Consteval
7567 : ConstexprSpecKind::Constexpr)
7568 : ConstexprSpecKind::Unspecified);
7569
7570 if (!Type->hasExceptionSpec()) {
7571 // C++2a [except.spec]p3:
7572 // If a declaration of a function does not have a noexcept-specifier
7573 // [and] is defaulted on its first declaration, [...] the exception
7574 // specification is as specified below
7575 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7577 EPI.ExceptionSpec.SourceDecl = MD;
7578 MD->setType(Context.getFunctionType(ReturnType,
7579 llvm::makeArrayRef(&ArgType,
7580 ExpectedParams),
7581 EPI));
7582 }
7583 }
7584
7585 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7586 if (First) {
7587 SetDeclDeleted(MD, MD->getLocation());
7588 if (!inTemplateInstantiation() && !HadError) {
7589 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7590 if (ShouldDeleteForTypeMismatch) {
7591 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7592 } else {
7593 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7594 }
7595 }
7596 if (ShouldDeleteForTypeMismatch && !HadError) {
7597 Diag(MD->getLocation(),
7598 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7599 }
7600 } else {
7601 // C++11 [dcl.fct.def.default]p4:
7602 // [For a] user-provided explicitly-defaulted function [...] if such a
7603 // function is implicitly defined as deleted, the program is ill-formed.
7604 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7605 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7606 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7607 HadError = true;
7608 }
7609 }
7610
7611 return HadError;
7612}
7613
7614namespace {
7615/// Helper class for building and checking a defaulted comparison.
7616///
7617/// Defaulted functions are built in two phases:
7618///
7619/// * First, the set of operations that the function will perform are
7620/// identified, and some of them are checked. If any of the checked
7621/// operations is invalid in certain ways, the comparison function is
7622/// defined as deleted and no body is built.
7623/// * Then, if the function is not defined as deleted, the body is built.
7624///
7625/// This is accomplished by performing two visitation steps over the eventual
7626/// body of the function.
7627template<typename Derived, typename ResultList, typename Result,
7628 typename Subobject>
7629class DefaultedComparisonVisitor {
7630public:
7631 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7632
7633 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7634 DefaultedComparisonKind DCK)
7635 : S(S), RD(RD), FD(FD), DCK(DCK) {
7636 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7637 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7638 // UnresolvedSet to avoid this copy.
7639 Fns.assign(Info->getUnqualifiedLookups().begin(),
7640 Info->getUnqualifiedLookups().end());
7641 }
7642 }
7643
7644 ResultList visit() {
7645 // The type of an lvalue naming a parameter of this function.
7646 QualType ParamLvalType =
7648
7649 ResultList Results;
7650
7651 switch (DCK) {
7652 case DefaultedComparisonKind::None:
7653 llvm_unreachable("not a defaulted comparison");
7654
7655 case DefaultedComparisonKind::Equal:
7656 case DefaultedComparisonKind::ThreeWay:
7657 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7658 return Results;
7659
7660 case DefaultedComparisonKind::NotEqual:
7661 case DefaultedComparisonKind::Relational:
7662 Results.add(getDerived().visitExpandedSubobject(
7663 ParamLvalType, getDerived().getCompleteObject()));
7664 return Results;
7665 }
7666 llvm_unreachable("");
7667 }
7668
7669protected:
7670 Derived &getDerived() { return static_cast<Derived&>(*this); }
7671
7672 /// Visit the expanded list of subobjects of the given type, as specified in
7673 /// C++2a [class.compare.default].
7674 ///
7675 /// \return \c true if the ResultList object said we're done, \c false if not.
7676 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7677 Qualifiers Quals) {
7678 // C++2a [class.compare.default]p4:
7679 // The direct base class subobjects of C
7680 for (CXXBaseSpecifier &Base : Record->bases())
7681 if (Results.add(getDerived().visitSubobject(
7682 S.Context.getQualifiedType(Base.getType(), Quals),
7683 getDerived().getBase(&Base))))
7684 return true;
7685
7686 // followed by the non-static data members of C
7687 for (FieldDecl *Field : Record->fields()) {
7688 // Recursively expand anonymous structs.
7689 if (Field->isAnonymousStructOrUnion()) {
7690 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7691 Quals))
7692 return true;
7693 continue;
7694 }
7695
7696 // Figure out the type of an lvalue denoting this field.
7697 Qualifiers FieldQuals = Quals;
7698 if (Field->isMutable())
7699 FieldQuals.removeConst();
7700 QualType FieldType =
7701 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7702
7703 if (Results.add(getDerived().visitSubobject(
7704 FieldType, getDerived().getField(Field))))
7705 return true;
7706 }
7707
7708 // form a list of subobjects.
7709 return false;
7710 }
7711
7712 Result visitSubobject(QualType Type, Subobject Subobj) {
7713 // In that list, any subobject of array type is recursively expanded
7714 const ArrayType *AT = S.Context.getAsArrayType(Type);
7715 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7716 return getDerived().visitSubobjectArray(CAT->getElementType(),
7717 CAT->getSize(), Subobj);
7718 return getDerived().visitExpandedSubobject(Type, Subobj);
7719 }
7720
7721 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7722 Subobject Subobj) {
7723 return getDerived().visitSubobject(Type, Subobj);
7724 }
7725
7726protected:
7727 Sema &S;
7728 CXXRecordDecl *RD;
7729 FunctionDecl *FD;
7730 DefaultedComparisonKind DCK;
7732};
7733
7734/// Information about a defaulted comparison, as determined by
7735/// DefaultedComparisonAnalyzer.
7736struct DefaultedComparisonInfo {
7737 bool Deleted = false;
7738 bool Constexpr = true;
7739 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7740
7741 static DefaultedComparisonInfo deleted() {
7742 DefaultedComparisonInfo Deleted;
7743 Deleted.Deleted = true;
7744 return Deleted;
7745 }
7746
7747 bool add(const DefaultedComparisonInfo &R) {
7748 Deleted |= R.Deleted;
7749 Constexpr &= R.Constexpr;
7750 Category = commonComparisonType(Category, R.Category);
7751 return Deleted;
7752 }
7753};
7754
7755/// An element in the expanded list of subobjects of a defaulted comparison, as
7756/// specified in C++2a [class.compare.default]p4.
7757struct DefaultedComparisonSubobject {
7758 enum { CompleteObject, Member, Base } Kind;
7759 NamedDecl *Decl;
7760 SourceLocation Loc;
7761};
7762
7763/// A visitor over the notional body of a defaulted comparison that determines
7764/// whether that body would be deleted or constexpr.
7765class DefaultedComparisonAnalyzer
7766 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7767 DefaultedComparisonInfo,
7768 DefaultedComparisonInfo,
7769 DefaultedComparisonSubobject> {
7770public:
7771 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7772
7773private:
7774 DiagnosticKind Diagnose;
7775
7776public:
7777 using Base = DefaultedComparisonVisitor;
7778 using Result = DefaultedComparisonInfo;
7779 using Subobject = DefaultedComparisonSubobject;
7780
7781 friend Base;
7782
7783 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7784 DefaultedComparisonKind DCK,
7785 DiagnosticKind Diagnose = NoDiagnostics)
7786 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7787
7788 Result visit() {
7789 if ((DCK == DefaultedComparisonKind::Equal ||
7790 DCK == DefaultedComparisonKind::ThreeWay) &&
7791 RD->hasVariantMembers()) {
7792 // C++2a [class.compare.default]p2 [P2002R0]:
7793 // A defaulted comparison operator function for class C is defined as
7794 // deleted if [...] C has variant members.
7795 if (Diagnose == ExplainDeleted) {
7796 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7797 << FD << RD->isUnion() << RD;
7798 }
7799 return Result::deleted();
7800 }
7801
7802 return Base::visit();
7803 }
7804
7805private:
7806 Subobject getCompleteObject() {
7807 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7808 }
7809
7810 Subobject getBase(CXXBaseSpecifier *Base) {
7811 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7812 Base->getBaseTypeLoc()};
7813 }
7814
7815 Subobject getField(FieldDecl *Field) {
7816 return Subobject{Subobject::Member, Field, Field->getLocation()};
7817 }
7818
7819 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7820 // C++2a [class.compare.default]p2 [P2002R0]:
7821 // A defaulted <=> or == operator function for class C is defined as
7822 // deleted if any non-static data member of C is of reference type
7823 if (Type->isReferenceType()) {
7824 if (Diagnose == ExplainDeleted) {
7825 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7826 << FD << RD;
7827 }
7828 return Result::deleted();
7829 }
7830
7831 // [...] Let xi be an lvalue denoting the ith element [...]
7833 Expr *Args[] = {&Xi, &Xi};
7834
7835 // All operators start by trying to apply that same operator recursively.
7837 assert(OO != OO_None && "not an overloaded operator!");
7838 return visitBinaryOperator(OO, Args, Subobj);
7839 }
7840
7841 Result
7842 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7843 Subobject Subobj,
7844 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7845 // Note that there is no need to consider rewritten candidates here if
7846 // we've already found there is no viable 'operator<=>' candidate (and are
7847 // considering synthesizing a '<=>' from '==' and '<').
7848 OverloadCandidateSet CandidateSet(
7851 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7852
7853 /// C++2a [class.compare.default]p1 [P2002R0]:
7854 /// [...] the defaulted function itself is never a candidate for overload
7855 /// resolution [...]
7856 CandidateSet.exclude(FD);
7857
7858 if (Args[0]->getType()->isOverloadableType())
7859 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7860 else
7861 // FIXME: We determine whether this is a valid expression by checking to
7862 // see if there's a viable builtin operator candidate for it. That isn't
7863 // really what the rules ask us to do, but should give the right results.
7864 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7865
7866 Result R;
7867
7869 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7870 case OR_Success: {
7871 // C++2a [class.compare.secondary]p2 [P2002R0]:
7872 // The operator function [...] is defined as deleted if [...] the
7873 // candidate selected by overload resolution is not a rewritten
7874 // candidate.
7875 if ((DCK == DefaultedComparisonKind::NotEqual ||
7876 DCK == DefaultedComparisonKind::Relational) &&
7877 !Best->RewriteKind) {
7878 if (Diagnose == ExplainDeleted) {
7879 if (Best->Function) {
7880 S.Diag(Best->Function->getLocation(),
7881 diag::note_defaulted_comparison_not_rewritten_callee)
7882 << FD;
7883 } else {
7884 assert(Best->Conversions.size() == 2 &&
7885 Best->Conversions[0].isUserDefined() &&
7886 "non-user-defined conversion from class to built-in "
7887 "comparison");
7888 S.Diag(Best->Conversions[0]
7889 .UserDefined.FoundConversionFunction.getDecl()
7890 ->getLocation(),
7891 diag::note_defaulted_comparison_not_rewritten_conversion)
7892 << FD;
7893 }
7894 }
7895 return Result::deleted();
7896 }
7897
7898 // Throughout C++2a [class.compare]: if overload resolution does not
7899 // result in a usable function, the candidate function is defined as
7900 // deleted. This requires that we selected an accessible function.
7901 //
7902 // Note that this only considers the access of the function when named
7903 // within the type of the subobject, and not the access path for any
7904 // derived-to-base conversion.
7905 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7906 if (ArgClass && Best->FoundDecl.getDecl() &&
7907 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7908 QualType ObjectType = Subobj.Kind == Subobject::Member
7909 ? Args[0]->getType()
7910 : S.Context.getRecordType(RD);
7912 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7913 Diagnose == ExplainDeleted
7914 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7915 << FD << Subobj.Kind << Subobj.Decl
7916 : S.PDiag()))
7917 return Result::deleted();
7918 }
7919
7920 bool NeedsDeducing =
7921 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7922
7923 if (FunctionDecl *BestFD = Best->Function) {
7924 // C++2a [class.compare.default]p3 [P2002R0]:
7925 // A defaulted comparison function is constexpr-compatible if
7926 // [...] no overlod resolution performed [...] results in a
7927 // non-constexpr function.
7928 assert(!BestFD->isDeleted() && "wrong overload resolution result");
7929 // If it's not constexpr, explain why not.
7930 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7931 if (Subobj.Kind != Subobject::CompleteObject)
7932 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7933 << Subobj.Kind << Subobj.Decl;
7934 S.Diag(BestFD->getLocation(),
7935 diag::note_defaulted_comparison_not_constexpr_here);
7936 // Bail out after explaining; we don't want any more notes.
7937 return Result::deleted();
7938 }
7939 R.Constexpr &= BestFD->isConstexpr();
7940
7941 if (NeedsDeducing) {
7942 // If any callee has an undeduced return type, deduce it now.
7943 // FIXME: It's not clear how a failure here should be handled. For
7944 // now, we produce an eager diagnostic, because that is forward
7945 // compatible with most (all?) other reasonable options.
7946 if (BestFD->getReturnType()->isUndeducedType() &&
7947 S.DeduceReturnType(BestFD, FD->getLocation(),
7948 /*Diagnose=*/false)) {
7949 // Don't produce a duplicate error when asked to explain why the
7950 // comparison is deleted: we diagnosed that when initially checking
7951 // the defaulted operator.
7952 if (Diagnose == NoDiagnostics) {
7953 S.Diag(
7954 FD->getLocation(),
7955 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7956 << Subobj.Kind << Subobj.Decl;
7957 S.Diag(
7958 Subobj.Loc,
7959 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7960 << Subobj.Kind << Subobj.Decl;
7961 S.Diag(BestFD->getLocation(),
7962 diag::note_defaulted_comparison_cannot_deduce_callee)
7963 << Subobj.Kind << Subobj.Decl;
7964 }
7965 return Result::deleted();
7966 }
7968 BestFD->getCallResultType());
7969 if (!Info) {
7970 if (Diagnose == ExplainDeleted) {
7971 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7972 << Subobj.Kind << Subobj.Decl
7973 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7974 S.Diag(BestFD->getLocation(),
7975 diag::note_defaulted_comparison_cannot_deduce_callee)
7976 << Subobj.Kind << Subobj.Decl;
7977 }
7978 return Result::deleted();
7979 }
7980 R.Category = Info->Kind;
7981 }
7982 } else {
7983 QualType T = Best->BuiltinParamTypes[0];
7984 assert(T == Best->BuiltinParamTypes[1] &&
7985 "builtin comparison for different types?");
7986 assert(Best->BuiltinParamTypes[2].isNull() &&
7987 "invalid builtin comparison");
7988
7989 if (NeedsDeducing) {
7992 assert(Cat && "no category for builtin comparison?");
7993 R.Category = *Cat;
7994 }
7995 }
7996
7997 // Note that we might be rewriting to a different operator. That call is
7998 // not considered until we come to actually build the comparison function.
7999 break;
8000 }
8001
8002 case OR_Ambiguous:
8003 if (Diagnose == ExplainDeleted) {
8004 unsigned Kind = 0;
8005 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8006 Kind = OO == OO_EqualEqual ? 1 : 2;
8007 CandidateSet.NoteCandidates(
8009 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8010 << FD << Kind << Subobj.Kind << Subobj.Decl),
8011 S, OCD_AmbiguousCandidates, Args);
8012 }
8013 R = Result::deleted();
8014 break;
8015
8016 case OR_Deleted:
8017 if (Diagnose == ExplainDeleted) {
8018 if ((DCK == DefaultedComparisonKind::NotEqual ||
8019 DCK == DefaultedComparisonKind::Relational) &&
8020 !Best->RewriteKind) {
8021 S.Diag(Best->Function->getLocation(),
8022 diag::note_defaulted_comparison_not_rewritten_callee)
8023 << FD;
8024 } else {
8025 S.Diag(Subobj.Loc,
8026 diag::note_defaulted_comparison_calls_deleted)
8027 << FD << Subobj.Kind << Subobj.Decl;
8028 S.NoteDeletedFunction(Best->Function);
8029 }
8030 }
8031 R = Result::deleted();
8032 break;
8033
8035 // If there's no usable candidate, we're done unless we can rewrite a
8036 // '<=>' in terms of '==' and '<'.
8037 if (OO == OO_Spaceship &&
8039 // For any kind of comparison category return type, we need a usable
8040 // '==' and a usable '<'.
8041 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8042 &CandidateSet)))
8043 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8044 break;
8045 }
8046
8047 if (Diagnose == ExplainDeleted) {
8048 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8049 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8050
8051 // For a three-way comparison, list both the candidates for the
8052 // original operator and the candidates for the synthesized operator.
8053 if (SpaceshipCandidates) {
8054 SpaceshipCandidates->NoteCandidates(
8055 S, Args,
8056 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8057 Args, FD->getLocation()));
8058 S.Diag(Subobj.Loc,
8059 diag::note_defaulted_comparison_no_viable_function_synthesized)
8060 << (OO == OO_EqualEqual ? 0 : 1);
8061 }
8062
8063 CandidateSet.NoteCandidates(
8064 S, Args,
8065 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8066 FD->getLocation()));
8067 }
8068 R = Result::deleted();
8069 break;
8070 }
8071
8072 return R;
8073 }
8074};
8075
8076/// A list of statements.
8077struct StmtListResult {
8078 bool IsInvalid = false;
8080
8081 bool add(const StmtResult &S) {
8082 IsInvalid |= S.isInvalid();
8083 if (IsInvalid)
8084 return true;
8085 Stmts.push_back(S.get());
8086 return false;
8087 }
8088};
8089
8090/// A visitor over the notional body of a defaulted comparison that synthesizes
8091/// the actual body.
8092class DefaultedComparisonSynthesizer
8093 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8094 StmtListResult, StmtResult,
8095 std::pair<ExprResult, ExprResult>> {
8096 SourceLocation Loc;
8097 unsigned ArrayDepth = 0;
8098
8099public:
8100 using Base = DefaultedComparisonVisitor;
8101 using ExprPair = std::pair<ExprResult, ExprResult>;
8102
8103 friend Base;
8104
8105 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8106 DefaultedComparisonKind DCK,
8107 SourceLocation BodyLoc)
8108 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8109
8110 /// Build a suitable function body for this defaulted comparison operator.
8111 StmtResult build() {
8112 Sema::CompoundScopeRAII CompoundScope(S);
8113
8114 StmtListResult Stmts = visit();
8115 if (Stmts.IsInvalid)
8116 return StmtError();
8117
8118 ExprResult RetVal;
8119 switch (DCK) {
8120 case DefaultedComparisonKind::None:
8121 llvm_unreachable("not a defaulted comparison");
8122
8123 case DefaultedComparisonKind::Equal: {
8124 // C++2a [class.eq]p3:
8125 // [...] compar[e] the corresponding elements [...] until the first
8126 // index i where xi == yi yields [...] false. If no such index exists,
8127 // V is true. Otherwise, V is false.
8128 //
8129 // Join the comparisons with '&&'s and return the result. Use a right
8130 // fold (traversing the conditions right-to-left), because that
8131 // short-circuits more naturally.
8132 auto OldStmts = std::move(Stmts.Stmts);
8133 Stmts.Stmts.clear();
8134 ExprResult CmpSoFar;
8135 // Finish a particular comparison chain.
8136 auto FinishCmp = [&] {
8137 if (Expr *Prior = CmpSoFar.get()) {
8138 // Convert the last expression to 'return ...;'
8139 if (RetVal.isUnset() && Stmts.Stmts.empty())
8140 RetVal = CmpSoFar;
8141 // Convert any prior comparison to 'if (!(...)) return false;'
8142 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8143 return true;
8144 CmpSoFar = ExprResult();
8145 }
8146 return false;
8147 };
8148 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8149 Expr *E = dyn_cast<Expr>(EAsStmt);
8150 if (!E) {
8151 // Found an array comparison.
8152 if (FinishCmp() || Stmts.add(EAsStmt))
8153 return StmtError();
8154 continue;
8155 }
8156
8157 if (CmpSoFar.isUnset()) {
8158 CmpSoFar = E;
8159 continue;
8160 }
8161 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8162 if (CmpSoFar.isInvalid())
8163 return StmtError();
8164 }
8165 if (FinishCmp())
8166 return StmtError();
8167 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8168 // If no such index exists, V is true.
8169 if (RetVal.isUnset())
8170 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8171 break;
8172 }
8173
8174 case DefaultedComparisonKind::ThreeWay: {
8175 // Per C++2a [class.spaceship]p3, as a fallback add:
8176 // return static_cast<R>(std::strong_ordering::equal);
8178 ComparisonCategoryType::StrongOrdering, Loc,
8179 Sema::ComparisonCategoryUsage::DefaultedOperator);
8180 if (StrongOrdering.isNull())
8181 return StmtError();
8183 .getValueInfo(ComparisonCategoryResult::Equal)
8184 ->VD;
8185 RetVal = getDecl(EqualVD);
8186 if (RetVal.isInvalid())
8187 return StmtError();
8188 RetVal = buildStaticCastToR(RetVal.get());
8189 break;
8190 }
8191
8192 case DefaultedComparisonKind::NotEqual:
8193 case DefaultedComparisonKind::Relational:
8194 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8195 break;
8196 }
8197
8198 // Build the final return statement.
8199 if (RetVal.isInvalid())
8200 return StmtError();
8201 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8202 if (ReturnStmt.isInvalid())
8203 return StmtError();
8204 Stmts.Stmts.push_back(ReturnStmt.get());
8205
8206 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8207 }
8208
8209private:
8210 ExprResult getDecl(ValueDecl *VD) {
8211 return S.BuildDeclarationNameExpr(
8212 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8213 }
8214
8215 ExprResult getParam(unsigned I) {
8216 ParmVarDecl *PD = FD->getParamDecl(I);
8217 return getDecl(PD);
8218 }
8219
8220 ExprPair getCompleteObject() {
8221 unsigned Param = 0;
8222 ExprResult LHS;
8223 if (isa<CXXMethodDecl>(FD)) {
8224 // LHS is '*this'.
8225 LHS = S.ActOnCXXThis(Loc);
8226 if (!LHS.isInvalid())
8227 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8228 } else {
8229 LHS = getParam(Param++);
8230 }
8231 ExprResult RHS = getParam(Param++);
8232 assert(Param == FD->getNumParams());
8233 return {LHS, RHS};
8234 }
8235
8236 ExprPair getBase(CXXBaseSpecifier *Base) {
8237 ExprPair Obj = getCompleteObject();
8238 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8239 return {ExprError(), ExprError()};
8240 CXXCastPath Path = {Base};
8241 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8242 CK_DerivedToBase, VK_LValue, &Path),
8243 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8244 CK_DerivedToBase, VK_LValue, &Path)};
8245 }
8246
8247 ExprPair getField(FieldDecl *Field) {
8248 ExprPair Obj = getCompleteObject();
8249 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8250 return {ExprError(), ExprError()};
8251
8252 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8253 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8254 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8255 CXXScopeSpec(), Field, Found, NameInfo),
8256 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8257 CXXScopeSpec(), Field, Found, NameInfo)};
8258 }
8259
8260 // FIXME: When expanding a subobject, register a note in the code synthesis
8261 // stack to say which subobject we're comparing.
8262
8263 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8264 if (Cond.isInvalid())
8265 return StmtError();
8266
8267 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8268 if (NotCond.isInvalid())
8269 return StmtError();
8270
8271 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8272 assert(!False.isInvalid() && "should never fail");
8273 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8274 if (ReturnFalse.isInvalid())
8275 return StmtError();
8276
8277 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8278 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8279 Sema::ConditionKind::Boolean),
8280 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8281 }
8282
8283 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8284 ExprPair Subobj) {
8285 QualType SizeType = S.Context.getSizeType();
8286 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8287
8288 // Build 'size_t i$n = 0'.
8289 IdentifierInfo *IterationVarName = nullptr;
8290 {
8291 SmallString<8> Str;
8292 llvm::raw_svector_ostream OS(Str);
8293 OS << "i" << ArrayDepth;
8294 IterationVarName = &S.Context.Idents.get(OS.str());
8295 }
8296 VarDecl *IterationVar = VarDecl::Create(
8297 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8298 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8299 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8300 IterationVar->setInit(
8301 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8302 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8303
8304 auto IterRef = [&] {
8306 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8307 IterationVar);
8308 assert(!Ref.isInvalid() && "can't reference our own variable?");
8309 return Ref.get();
8310 };
8311
8312 // Build 'i$n != Size'.
8314 Loc, BO_NE, IterRef(),
8315 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8316 assert(!Cond.isInvalid() && "should never fail");
8317
8318 // Build '++i$n'.
8319 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8320 assert(!Inc.isInvalid() && "should never fail");
8321
8322 // Build 'a[i$n]' and 'b[i$n]'.
8323 auto Index = [&](ExprResult E) {
8324 if (E.isInvalid())
8325 return ExprError();
8326 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8327 };
8328 Subobj.first = Index(Subobj.first);
8329 Subobj.second = Index(Subobj.second);
8330
8331 // Compare the array elements.
8332 ++ArrayDepth;
8333 StmtResult Substmt = visitSubobject(Type, Subobj);
8334 --ArrayDepth;
8335
8336 if (Substmt.isInvalid())
8337 return StmtError();
8338
8339 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8340 // For outer levels or for an 'operator<=>' we already have a suitable
8341 // statement that returns as necessary.
8342 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8343 assert(DCK == DefaultedComparisonKind::Equal &&
8344 "should have non-expression statement");
8345 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8346 if (Substmt.isInvalid())
8347 return StmtError();
8348 }
8349
8350 // Build 'for (...) ...'
8351 return S.ActOnForStmt(Loc, Loc, Init,
8352 S.ActOnCondition(nullptr, Loc, Cond.get(),
8353 Sema::ConditionKind::Boolean),
8354 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8355 Substmt.get());
8356 }
8357
8358 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8359 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8360 return StmtError();
8361
8364 ExprResult Op;
8365 if (Type->isOverloadableType())
8366 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8367 Obj.second.get(), /*PerformADL=*/true,
8368 /*AllowRewrittenCandidates=*/true, FD);
8369 else
8370 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8371 if (Op.isInvalid())
8372 return StmtError();
8373
8374 switch (DCK) {
8375 case DefaultedComparisonKind::None:
8376 llvm_unreachable("not a defaulted comparison");
8377
8378 case DefaultedComparisonKind::Equal:
8379 // Per C++2a [class.eq]p2, each comparison is individually contextually
8380 // converted to bool.
8382 if (Op.isInvalid())
8383 return StmtError();
8384 return Op.get();
8385
8386 case DefaultedComparisonKind::ThreeWay: {
8387 // Per C++2a [class.spaceship]p3, form:
8388 // if (R cmp = static_cast<R>(op); cmp != 0)
8389 // return cmp;
8390 QualType R = FD->getReturnType();
8391 Op = buildStaticCastToR(Op.get());
8392 if (Op.isInvalid())
8393 return StmtError();
8394
8395 // R cmp = ...;
8396 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8397 VarDecl *VD =
8398 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8400 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8401 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8402
8403 // cmp != 0
8404 ExprResult VDRef = getDecl(VD);
8405 if (VDRef.isInvalid())
8406 return StmtError();
8407 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8408 Expr *Zero =
8409 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8410 ExprResult Comp;
8411 if (VDRef.get()->getType()->isOverloadableType())
8412 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8413 true, FD);
8414 else
8415 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8416 if (Comp.isInvalid())
8417 return StmtError();
8419 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8420 if (Cond.isInvalid())
8421 return StmtError();
8422
8423 // return cmp;
8424 VDRef = getDecl(VD);
8425 if (VDRef.isInvalid())
8426 return StmtError();
8427 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8428 if (ReturnStmt.isInvalid())
8429 return StmtError();
8430
8431 // if (...)
8432 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8433 Loc, ReturnStmt.get(),
8434 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8435 }
8436
8437 case DefaultedComparisonKind::NotEqual:
8438 case DefaultedComparisonKind::Relational:
8439 // C++2a [class.compare.secondary]p2:
8440 // Otherwise, the operator function yields x @ y.
8441 return Op.get();
8442 }
8443 llvm_unreachable("");
8444 }
8445
8446 /// Build "static_cast<R>(E)".
8447 ExprResult buildStaticCastToR(Expr *E) {
8448 QualType R = FD->getReturnType();
8449 assert(!R->isUndeducedType() && "type should have been deduced already");
8450
8451 // Don't bother forming a no-op cast in the common case.
8452 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8453 return E;
8454 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8455 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8456 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8457 }
8458};
8459}
8460
8461/// Perform the unqualified lookups that might be needed to form a defaulted
8462/// comparison function for the given operator.
8464 UnresolvedSetImpl &Operators,
8466 auto Lookup = [&](OverloadedOperatorKind OO) {
8467 Self.LookupOverloadedOperatorName(OO, S, Operators);
8468 };
8469
8470 // Every defaulted operator looks up itself.
8471 Lookup(Op);
8472 // ... and the rewritten form of itself, if any.
8474 Lookup(ExtraOp);
8475
8476 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8477 // synthesize a three-way comparison from '<' and '=='. In a dependent
8478 // context, we also need to look up '==' in case we implicitly declare a
8479 // defaulted 'operator=='.
8480 if (Op == OO_Spaceship) {
8481 Lookup(OO_ExclaimEqual);
8482 Lookup(OO_Less);
8483 Lookup(OO_EqualEqual);
8484 }
8485}
8486
8489 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8490
8491 // Perform any unqualified lookups we're going to need to default this
8492 // function.
8493 if (S) {
8494 UnresolvedSet<32> Operators;
8495 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8496 FD->getOverloadedOperator());
8498 Context, Operators.pairs()));
8499 }
8500
8501 // C++2a [class.compare.default]p1:
8502 // A defaulted comparison operator function for some class C shall be a
8503 // non-template function declared in the member-specification of C that is
8504 // -- a non-static const member of C having one parameter of type
8505 // const C&, or
8506 // -- a friend of C having two parameters of type const C& or two
8507 // parameters of type C.
8508
8509 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8510 bool IsMethod = isa<CXXMethodDecl>(FD);
8511 if (IsMethod) {
8512 auto *MD = cast<CXXMethodDecl>(FD);
8513 assert(!MD->isStatic() && "comparison function cannot be a static member");
8514
8515 // If we're out-of-class, this is the class we're comparing.
8516 if (!RD)
8517 RD = MD->getParent();
8518
8519 if (!MD->isConst()) {
8520 SourceLocation InsertLoc;
8521 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8522 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8523 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8524 // corresponding defaulted 'operator<=>' already.
8525 if (!MD->isImplicit()) {
8526 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8527 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8528 }
8529
8530 // Add the 'const' to the type to recover.
8531 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8532 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8533 EPI.TypeQuals.addConst();
8534 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8535 FPT->getParamTypes(), EPI));
8536 }
8537 }
8538
8539 if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8540 // Let's not worry about using a variadic template pack here -- who would do
8541 // such a thing?
8542 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8543 << int(IsMethod) << int(DCK);
8544 return true;
8545 }
8546
8547 const ParmVarDecl *KnownParm = nullptr;
8548 for (const ParmVarDecl *Param : FD->parameters()) {
8549 QualType ParmTy = Param->getType();
8550 if (ParmTy->isDependentType())
8551 continue;
8552 if (!KnownParm) {
8553 auto CTy = ParmTy;
8554 // Is it `T const &`?
8555 bool Ok = !IsMethod;
8556 QualType ExpectedTy;
8557 if (RD)
8558 ExpectedTy = Context.getRecordType(RD);
8559 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8560 CTy = Ref->getPointeeType();
8561 if (RD)
8562 ExpectedTy.addConst();
8563 Ok = true;
8564 }
8565
8566 // Is T a class?
8567 if (!Ok) {
8568 } else if (RD) {
8569 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8570 Ok = false;
8571 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8572 RD = cast<CXXRecordDecl>(CRD);
8573 } else {
8574 Ok = false;
8575 }
8576
8577 if (Ok) {
8578 KnownParm = Param;
8579 } else {
8580 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8581 // corresponding defaulted 'operator<=>' already.
8582 if (!FD->isImplicit()) {
8583 if (RD) {
8584 QualType PlainTy = Context.getRecordType(RD);
8585 QualType RefTy =
8586 Context.getLValueReferenceType(PlainTy.withConst());
8587 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8588 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8589 << Param->getSourceRange();
8590 } else {
8591 assert(!IsMethod && "should know expected type for method");
8592 Diag(FD->getLocation(),
8593 diag::err_defaulted_comparison_param_unknown)
8594 << int(DCK) << ParmTy << Param->getSourceRange();
8595 }
8596 }
8597 return true;
8598 }
8599 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8600 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8601 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8602 << ParmTy << Param->getSourceRange();
8603 return true;
8604 }
8605 }
8606
8607 assert(RD && "must have determined class");
8608 if (IsMethod) {
8609 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8610 // In-class, must be a friend decl.
8611 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8612 } else {
8613 // Out of class, require the defaulted comparison to be a friend (of a
8614 // complete type).
8615 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8616 diag::err_defaulted_comparison_not_friend, int(DCK),
8617 int(1)))
8618 return true;
8619
8620 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8621 return FD->getCanonicalDecl() ==
8622 F->getFriendDecl()->getCanonicalDecl();
8623 })) {
8624 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8625 << int(DCK) << int(0) << RD;
8626 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8627 return true;
8628 }
8629 }
8630
8631 // C++2a [class.eq]p1, [class.rel]p1:
8632 // A [defaulted comparison other than <=>] shall have a declared return
8633 // type bool.
8634 if (DCK != DefaultedComparisonKind::ThreeWay &&
8636 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8637 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8638 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8639 << FD->getReturnTypeSourceRange();
8640 return true;
8641 }
8642 // C++2a [class.spaceship]p2 [P2002R0]:
8643 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8644 // R shall not contain a placeholder type.
8645 if (DCK == DefaultedComparisonKind::ThreeWay &&
8647 !Context.hasSameType(FD->getDeclaredReturnType(),
8648 Context.getAutoDeductType())) {
8649 Diag(FD->getLocation(),
8650 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8651 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8652 << FD->getReturnTypeSourceRange();
8653 return true;
8654 }
8655
8656 // For a defaulted function in a dependent class, defer all remaining checks
8657 // until instantiation.
8658 if (RD->isDependentType())
8659 return false;
8660
8661 // Determine whether the function should be defined as deleted.
8662 DefaultedComparisonInfo Info =
8663 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8664
8665 bool First = FD == FD->getCanonicalDecl();
8666
8667 // If we want to delete the function, then do so; there's nothing else to
8668 // check in that case.
8669 if (Info.Deleted) {
8670 if (!First) {
8671 // C++11 [dcl.fct.def.default]p4:
8672 // [For a] user-provided explicitly-defaulted function [...] if such a
8673 // function is implicitly defined as deleted, the program is ill-formed.
8674 //
8675 // This is really just a consequence of the general rule that you can
8676 // only delete a function on its first declaration.
8677 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8678 << FD->isImplicit() << (int)DCK;
8679 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8680 DefaultedComparisonAnalyzer::ExplainDeleted)
8681 .visit();
8682 return true;
8683 }
8684
8685 SetDeclDeleted(FD, FD->getLocation());
8686 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8687 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8688 << (int)DCK;
8689 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8690 DefaultedComparisonAnalyzer::ExplainDeleted)
8691 .visit();
8692 }
8693 return false;
8694 }
8695
8696 // C++2a [class.spaceship]p2:
8697 // The return type is deduced as the common comparison type of R0, R1, ...
8698 if (DCK == DefaultedComparisonKind::ThreeWay &&
8701 if (RetLoc.isInvalid())
8702 RetLoc = FD->getBeginLoc();
8703 // FIXME: Should we really care whether we have the complete type and the
8704 // 'enumerator' constants here? A forward declaration seems sufficient.
8705 QualType Cat = CheckComparisonCategoryType(
8706 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8707 if (Cat.isNull())
8708 return true;
8710 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8711 }
8712
8713 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8714 // An explicitly-defaulted function that is not defined as deleted may be
8715 // declared constexpr or consteval only if it is constexpr-compatible.
8716 // C++2a [class.compare.default]p3 [P2002R0]:
8717 // A defaulted comparison function is constexpr-compatible if it satisfies
8718 // the requirements for a constexpr function [...]
8719 // The only relevant requirements are that the parameter and return types are
8720 // literal types. The remaining conditions are checked by the analyzer.
8721 if (FD->isConstexpr()) {
8722 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8723 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8724 !Info.Constexpr) {
8725 Diag(FD->getBeginLoc(),
8726 diag::err_incorrect_defaulted_comparison_constexpr)
8727 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8728 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8729 DefaultedComparisonAnalyzer::ExplainConstexpr)
8730 .visit();
8731 }
8732 }
8733
8734 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8735 // If a constexpr-compatible function is explicitly defaulted on its first
8736 // declaration, it is implicitly considered to be constexpr.
8737 // FIXME: Only applying this to the first declaration seems problematic, as
8738 // simple reorderings can affect the meaning of the program.
8739 if (First && !FD->isConstexpr() && Info.Constexpr)
8740 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8741
8742 // C++2a [except.spec]p3:
8743 // If a declaration of a function does not have a noexcept-specifier
8744 // [and] is defaulted on its first declaration, [...] the exception
8745 // specification is as specified below
8746 if (FD->getExceptionSpecType() == EST_None) {
8747 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8750 EPI.ExceptionSpec.SourceDecl = FD;
8751 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8752 FPT->getParamTypes(), EPI));
8753 }
8754
8755 return false;
8756}
8757
8759 FunctionDecl *Spaceship) {
8762 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8763 Ctx.Entity = Spaceship;
8764 pushCodeSynthesisContext(Ctx);
8765
8766 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8767 EqualEqual->setImplicit();
8768
8769 popCodeSynthesisContext();
8770}
8771
8774 assert(FD->isDefaulted() && !FD->isDeleted() &&
8776 if (FD->willHaveBody() || FD->isInvalidDecl())
8777 return;
8778
8780
8781 // Add a context note for diagnostics produced after this point.
8782 Scope.addContextNote(UseLoc);
8783
8784 {
8785 // Build and set up the function body.
8786 // The first parameter has type maybe-ref-to maybe-const T, use that to get
8787 // the type of the class being compared.
8788 auto PT = FD->getParamDecl(0)->getType();
8789 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8790 SourceLocation BodyLoc =
8791 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8792 StmtResult Body =
8793 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8794 if (Body.isInvalid()) {
8795 FD->setInvalidDecl();
8796 return;
8797 }
8798 FD->setBody(Body.get());
8799 FD->markUsed(Context);
8800 }
8801
8802 // The exception specification is needed because we are defining the
8803 // function. Note that this will reuse the body we just built.
8804 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8805
8806 if (ASTMutationListener *L = getASTMutationListener())
8807 L->CompletedImplicitDefinition(FD);
8808}
8809
8812 FunctionDecl *FD,
8814 ComputingExceptionSpec CES(S, FD, Loc);
8816
8817 if (FD->isInvalidDecl())
8818 return ExceptSpec;
8819
8820 // The common case is that we just defined the comparison function. In that
8821 // case, just look at whether the body can throw.
8822 if (FD->hasBody()) {
8823 ExceptSpec.CalledStmt(FD->getBody());
8824 } else {
8825 // Otherwise, build a body so we can check it. This should ideally only
8826 // happen when we're not actually marking the function referenced. (This is
8827 // only really important for efficiency: we don't want to build and throw
8828 // away bodies for comparison functions more than we strictly need to.)
8829
8830 // Pretend to synthesize the function body in an unevaluated context.
8831 // Note that we can't actually just go ahead and define the function here:
8832 // we are not permitted to mark its callees as referenced.
8835 S, Sema::ExpressionEvaluationContext::Unevaluated);
8836
8838 SourceLocation BodyLoc =
8839 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8840 StmtResult Body =
8841 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8842 if (!Body.isInvalid())
8843 ExceptSpec.CalledStmt(Body.get());
8844
8845 // FIXME: Can we hold onto this body and just transform it to potentially
8846 // evaluated when we're asked to define the function rather than rebuilding
8847 // it? Either that, or we should only build the bits of the body that we
8848 // need (the expressions, not the statements).
8849 }
8850
8851 return ExceptSpec;
8852}
8853
8855 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8856 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8857
8858 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8859 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8860
8861 // Perform any deferred checking of exception specifications for virtual
8862 // destructors.
8863 for (auto &Check : Overriding)
8864 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8865
8866 // Perform any deferred checking of exception specifications for befriended
8867 // special members.
8868 for (auto &Check : Equivalent)
8869 CheckEquivalentExceptionSpec(Check.second, Check.first);
8870}
8871
8872namespace {
8873/// CRTP base class for visiting operations performed by a special member
8874/// function (or inherited constructor).
8875template<typename Derived>
8876struct SpecialMemberVisitor {
8877 Sema &S;
8878 CXXMethodDecl *MD;
8881
8882 // Properties of the special member, computed for convenience.
8883 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8884
8885 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8887 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8888 switch (CSM) {
8892 IsConstructor = true;
8893 break;
8896 IsAssignment = true;
8897 break;
8899 break;
8900 case Sema::CXXInvalid:
8901 llvm_unreachable("invalid special member kind");
8902 }
8903
8904 if (MD->getNumParams()) {
8905 if (const ReferenceType *RT =
8906 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8907 ConstArg = RT->getPointeeType().isConstQualified();
8908 }
8909 }
8910
8911 Derived &getDerived() { return static_cast<Derived&>(*this); }
8912
8913 /// Is this a "move" special member?
8914 bool isMove() const {
8915 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8916 }
8917
8918 /// Look up the corresponding special member in the given class.
8920 unsigned Quals, bool IsMutable) {
8921 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8922 ConstArg && !IsMutable);
8923 }
8924
8925 /// Look up the constructor for the specified base class to see if it's
8926 /// overridden due to this being an inherited constructor.
8927 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8928 if (!ICI)
8929 return {};
8930 assert(CSM == Sema::CXXDefaultConstructor);
8931 auto *BaseCtor =
8932 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8933 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8934 return MD;
8935 return {};
8936 }
8937
8938 /// A base or member subobject.
8939 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8940
8941 /// Get the location to use for a subobject in diagnostics.
8942 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8943 // FIXME: For an indirect virtual base, the direct base leading to
8944 // the indirect virtual base would be a more useful choice.
8945 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8946 return B->getBaseTypeLoc();
8947 else
8948 return Subobj.get<FieldDecl*>()->getLocation();
8949 }
8950
8951 enum BasesToVisit {
8952 /// Visit all non-virtual (direct) bases.
8953 VisitNonVirtualBases,
8954 /// Visit all direct bases, virtual or not.
8955 VisitDirectBases,
8956 /// Visit all non-virtual bases, and all virtual bases if the class
8957 /// is not abstract.
8958 VisitPotentiallyConstructedBases,
8959 /// Visit all direct or virtual bases.
8960 VisitAllBases
8961 };
8962
8963 // Visit the bases and members of the class.
8964 bool visit(BasesToVisit Bases) {
8965 CXXRecordDecl *RD = MD->getParent();
8966
8967 if (Bases == VisitPotentiallyConstructedBases)
8968 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8969
8970 for (auto &B : RD->bases())
8971 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8972 getDerived().visitBase(&B))
8973 return true;
8974
8975 if (Bases == VisitAllBases)
8976 for (auto &B : RD->vbases())
8977 if (getDerived().visitBase(&B))
8978 return true;
8979
8980 for (auto *F : RD->fields())
8981 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8982 getDerived().visitField(F))
8983 return true;
8984
8985 return false;
8986 }
8987};
8988}
8989
8990namespace {
8991struct SpecialMemberDeletionInfo
8992 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8993 bool Diagnose;
8994
8995 SourceLocation Loc;
8996
8997 bool AllFieldsAreConst;
8998
8999 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9001 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9002 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9003 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9004
9005 bool inUnion() const { return MD->getParent()->isUnion(); }
9006
9007 Sema::CXXSpecialMember getEffectiveCSM() {
9008 return ICI ? Sema::CXXInvalid : CSM;
9009 }
9010
9011 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9012
9013 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9014 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9015
9016 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9017 bool shouldDeleteForField(FieldDecl *FD);
9018 bool shouldDeleteForAllConstMembers();
9019
9020 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9021 unsigned Quals);
9022 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9024 bool IsDtorCallInCtor);
9025
9026 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9027};
9028}
9029
9030/// Is the given special member inaccessible when used on the given
9031/// sub-object.
9032bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9033 CXXMethodDecl *target) {
9034 /// If we're operating on a base class, the object type is the
9035 /// type of this special member.
9036 QualType objectTy;
9037 AccessSpecifier access = target->getAccess();
9038 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9039 objectTy = S.Context.getTypeDeclType(MD->getParent());
9040 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9041
9042 // If we're operating on a field, the object type is the type of the field.
9043 } else {
9044 objectTy = S.Context.getTypeDeclType(target->getParent());
9045 }
9046
9048 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9049}
9050
9051/// Check whether we should delete a special member due to the implicit
9052/// definition containing a call to a special member of a subobject.
9053bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9054 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9055 bool IsDtorCallInCtor) {
9056 CXXMethodDecl *Decl = SMOR.getMethod();
9057 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9058
9059 int DiagKind = -1;
9060
9062 DiagKind = !Decl ? 0 : 1;
9064 DiagKind = 2;
9065 else if (!isAccessible(Subobj, Decl))
9066 DiagKind = 3;
9067 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9068 !Decl->isTrivial()) {
9069 // A member of a union must have a trivial corresponding special member.
9070 // As a weird special case, a destructor call from a union's constructor
9071 // must be accessible and non-deleted, but need not be trivial. Such a
9072 // destructor is never actually called, but is semantically checked as
9073 // if it were.
9074 DiagKind = 4;
9075 }
9076
9077 if (DiagKind == -1)
9078 return false;
9079
9080 if (Diagnose) {
9081 if (Field) {
9082 S.Diag(Field->getLocation(),
9083 diag::note_deleted_special_member_class_subobject)
9084 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9085 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9086 } else {
9087 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9088 S.Diag(Base->getBeginLoc(),
9089 diag::note_deleted_special_member_class_subobject)
9090 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9091 << Base->getType() << DiagKind << IsDtorCallInCtor
9092 << /*IsObjCPtr*/false;
9093 }
9094
9095 if (DiagKind == 1)
9097 // FIXME: Explain inaccessibility if DiagKind == 3.
9098 }
9099
9100 return true;
9101}
9102
9103/// Check whether we should delete a special member function due to having a
9104/// direct or virtual base class or non-static data member of class type M.
9105bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9106 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9107 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9108 bool IsMutable = Field && Field->isMutable();
9109
9110 // C++11 [class.ctor]p5:
9111 // -- any direct or virtual base class, or non-static data member with no
9112 // brace-or-equal-initializer, has class type M (or array thereof) and
9113 // either M has no default constructor or overload resolution as applied
9114 // to M's default constructor results in an ambiguity or in a function
9115 // that is deleted or inaccessible
9116 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9117 // -- a direct or virtual base class B that cannot be copied/moved because
9118 // overload resolution, as applied to B's corresponding special member,
9119 // results in an ambiguity or a function that is deleted or inaccessible
9120 // from the defaulted special member
9121 // C++11 [class.dtor]p5:
9122 // -- any direct or virtual base class [...] has a type with a destructor
9123 // that is deleted or inaccessible
9124 if (!(CSM == Sema::CXXDefaultConstructor &&
9125 Field && Field->hasInClassInitializer()) &&
9126 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9127 false))
9128 return true;
9129
9130 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9131 // -- any direct or virtual base class or non-static data member has a
9132 // type with a destructor that is deleted or inaccessible
9133 if (IsConstructor) {
9136 false, false, false, false, false);
9137 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9138 return true;
9139 }
9140
9141 return false;
9142}
9143
9144bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9145 FieldDecl *FD, QualType FieldType) {
9146 // The defaulted special functions are defined as deleted if this is a variant
9147 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9148 // type under ARC.
9149 if (!FieldType.hasNonTrivialObjCLifetime())
9150 return false;
9151
9152 // Don't make the defaulted default constructor defined as deleted if the
9153 // member has an in-class initializer.
9155 return false;
9156
9157 if (Diagnose) {
9158 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9159 S.Diag(FD->getLocation(),
9160 diag::note_deleted_special_member_class_subobject)
9161 << getEffectiveCSM() << ParentClass << /*IsField*/true
9162 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9163 }
9164
9165 return true;
9166}
9167
9168/// Check whether we should delete a special member function due to the class
9169/// having a particular direct or virtual base class.
9170bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9171 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9172 // If program is correct, BaseClass cannot be null, but if it is, the error
9173 // must be reported elsewhere.
9174 if (!BaseClass)
9175 return false;
9176 // If we have an inheriting constructor, check whether we're calling an
9177 // inherited constructor instead of a default constructor.
9178 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9179 if (auto *BaseCtor = SMOR.getMethod()) {
9180 // Note that we do not check access along this path; other than that,
9181 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9182 // FIXME: Check that the base has a usable destructor! Sink this into
9183 // shouldDeleteForClassSubobject.
9184 if (BaseCtor->isDeleted() && Diagnose) {
9185 S.Diag(Base->getBeginLoc(),
9186 diag::note_deleted_special_member_class_subobject)
9187 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9188 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9189 << /*IsObjCPtr*/false;
9190 S.NoteDeletedFunction(BaseCtor);
9191 }
9192 return BaseCtor->isDeleted();
9193 }
9194 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9195}
9196
9197/// Check whether we should delete a special member function due to the class
9198/// having a particular non-static data member.
9199bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9200 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9201 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9202
9203 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9204 return true;
9205
9206 if (CSM == Sema::CXXDefaultConstructor) {
9207 // For a default constructor, all references must be initialized in-class
9208 // and, if a union, it must have a non-const member.
9209 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9210 if (Diagnose)
9211 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9212 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9213 return true;
9214 }
9215 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9216 // data member of const-qualified type (or array thereof) with no
9217 // brace-or-equal-initializer is not const-default-constructible.
9218 if (!inUnion() && FieldType.isConstQualified() &&
9219 !FD->hasInClassInitializer() &&
9220 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9221 if (Diagnose)
9222 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9223 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9224 return true;
9225 }
9226
9227 if (inUnion() && !FieldType.isConstQualified())
9228 AllFieldsAreConst = false;
9229 } else if (CSM == Sema::CXXCopyConstructor) {
9230 // For a copy constructor, data members must not be of rvalue reference
9231 // type.
9232 if (FieldType->isRValueReferenceType()) {
9233 if (Diagnose)
9234 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9235 << MD->getParent() << FD << FieldType;
9236 return true;
9237 }
9238 } else if (IsAssignment) {
9239 // For an assignment operator, data members must not be of reference type.
9240 if (FieldType->isReferenceType()) {
9241 if (Diagnose)
9242 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9243 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9244 return true;
9245 }
9246 if (!FieldRecord && FieldType.isConstQualified()) {
9247 // C++11 [class.copy]p23:
9248 // -- a non-static data member of const non-class type (or array thereof)
9249 if (Diagnose)
9250 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9251 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9252 return true;
9253 }
9254 }
9255
9256 if (FieldRecord) {
9257 // Some additional restrictions exist on the variant members.
9258 if (!inUnion() && FieldRecord->isUnion() &&
9259 FieldRecord->isAnonymousStructOrUnion()) {
9260 bool AllVariantFieldsAreConst = true;
9261
9262 // FIXME: Handle anonymous unions declared within anonymous unions.
9263 for (auto *UI : FieldRecord->fields()) {
9264 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9265
9266 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9267 return true;
9268
9269 if (!UnionFieldType.isConstQualified())
9270 AllVariantFieldsAreConst = false;
9271
9272 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9273 if (UnionFieldRecord &&
9274 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9275 UnionFieldType.getCVRQualifiers()))
9276 return true;
9277 }
9278
9279 // At least one member in each anonymous union must be non-const
9280 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9281 !FieldRecord->field_empty()) {
9282 if (Diagnose)
9283 S.Diag(FieldRecord->getLocation(),
9284 diag::note_deleted_default_ctor_all_const)
9285 << !!ICI << MD->getParent() << /*anonymous union*/1;
9286 return true;
9287 }
9288
9289 // Don't check the implicit member of the anonymous union type.
9290 // This is technically non-conformant but supported, and we have a
9291 // diagnostic for this elsewhere.
9292 return false;
9293 }
9294
9295 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9296 FieldType.getCVRQualifiers()))
9297 return true;
9298 }
9299
9300 return false;
9301}
9302
9303/// C++11 [class.ctor] p5:
9304/// A defaulted default constructor for a class X is defined as deleted if
9305/// X is a union and all of its variant members are of const-qualified type.
9306bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9307 // This is a silly definition, because it gives an empty union a deleted
9308 // default constructor. Don't do that.
9309 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9310 bool AnyFields = false;
9311 for (auto *F : MD->getParent()->fields())
9312 if ((AnyFields = !F->isUnnamedBitfield()))
9313 break;
9314 if (!AnyFields)
9315 return false;
9316 if (Diagnose)
9317 S.Diag(MD->getParent()->getLocation(),
9318 diag::note_deleted_default_ctor_all_const)
9319 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9320 return true;
9321 }
9322 return false;
9323}
9324
9325/// Determine whether a defaulted special member function should be defined as
9326/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9327/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9330 bool Diagnose) {
9331 if (MD->isInvalidDecl())
9332 return false;
9333 CXXRecordDecl *RD = MD->getParent();
9334 assert(!RD->isDependentType() && "do deletion after instantiation");
9335 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9336 return false;
9337
9338 // C++11 [expr.lambda.prim]p19:
9339 // The closure type associated with a lambda-expression has a
9340 // deleted (8.4.3) default constructor and a deleted copy
9341 // assignment operator.
9342 // C++2a adds back these operators if the lambda has no lambda-capture.
9344 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9345 if (Diagnose)
9346 Diag(RD->getLocation(), diag::note_lambda_decl);
9347 return true;
9348 }
9349
9350 // For an anonymous struct or union, the copy and assignment special members
9351 // will never be used, so skip the check. For an anonymous union declared at
9352 // namespace scope, the constructor and destructor are used.
9353 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9355 return false;
9356
9357 // C++11 [class.copy]p7, p18:
9358 // If the class definition declares a move constructor or move assignment
9359 // operator, an implicitly declared copy constructor or copy assignment
9360 // operator is defined as deleted.
9361 if (MD->isImplicit() &&
9362 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9363 CXXMethodDecl *UserDeclaredMove = nullptr;
9364
9365 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9366 // deletion of the corresponding copy operation, not both copy operations.
9367 // MSVC 2015 has adopted the standards conforming behavior.
9368 bool DeletesOnlyMatchingCopy =
9369 getLangOpts().MSVCCompat &&
9370 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9371
9373 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9374 if (!Diagnose) return true;
9375
9376 // Find any user-declared move constructor.
9377 for (auto *I : RD->ctors()) {
9378 if (I->isMoveConstructor()) {
9379 UserDeclaredMove = I;
9380 break;
9381 }
9382 }
9383 assert(UserDeclaredMove);
9384 } else if (RD->hasUserDeclaredMoveAssignment() &&
9385 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9386 if (!Diagnose) return true;
9387
9388 // Find any user-declared move assignment operator.
9389 for (auto *I : RD->methods()) {
9390 if (I->isMoveAssignmentOperator()) {
9391 UserDeclaredMove = I;
9392 break;
9393 }
9394 }
9395 assert(UserDeclaredMove);
9396 }
9397
9398 if (UserDeclaredMove) {
9399 Diag(UserDeclaredMove->getLocation(),
9400 diag::note_deleted_copy_user_declared_move)
9401 << (CSM == CXXCopyAssignment) << RD
9402 << UserDeclaredMove->isMoveAssignmentOperator();
9403 return true;
9404 }
9405 }
9406
9407 // Do access control from the special member function
9408 ContextRAII MethodContext(*this, MD);
9409
9410 // C++11 [class.dtor]p5:
9411 // -- for a virtual destructor, lookup of the non-array deallocation function
9412 // results in an ambiguity or in a function that is deleted or inaccessible
9413 if (CSM == CXXDestructor && MD->isVirtual()) {
9414 FunctionDecl *OperatorDelete = nullptr;
9415 DeclarationName Name =
9416 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9417 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9418 OperatorDelete, /*Diagnose*/false)) {
9419 if (Diagnose)
9420 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9421 return true;
9422 }
9423 }
9424
9425 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9426
9427 // Per DR1611, do not consider virtual bases of constructors of abstract
9428 // classes, since we are not going to construct them.
9429 // Per DR1658, do not consider virtual bases of destructors of abstract
9430 // classes either.
9431 // Per DR2180, for assignment operators we only assign (and thus only
9432 // consider) direct bases.
9433 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9434 : SMI.VisitPotentiallyConstructedBases))
9435 return true;
9436
9437 if (SMI.shouldDeleteForAllConstMembers())
9438 return true;
9439
9440 if (getLangOpts().CUDA) {
9441 // We should delete the special member in CUDA mode if target inference
9442 // failed.
9443 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9444 // is treated as certain special member, which may not reflect what special
9445 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9446 // expects CSM to match MD, therefore recalculate CSM.
9447 assert(ICI || CSM == getSpecialMember(MD));
9448 auto RealCSM = CSM;
9449 if (ICI)
9450 RealCSM = getSpecialMember(MD);
9451
9452 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9453 SMI.ConstArg, Diagnose);
9454 }
9455
9456 return false;
9457}
9458
9460 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9461 assert(DFK && "not a defaultable function");
9462 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9463
9464 if (DFK.isSpecialMember()) {
9465 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9466 nullptr, /*Diagnose=*/true);
9467 } else {
9468 DefaultedComparisonAnalyzer(
9469 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9470 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9471 .visit();
9472 }
9473}
9474
9475/// Perform lookup for a special member of the specified kind, and determine
9476/// whether it is trivial. If the triviality can be determined without the
9477/// lookup, skip it. This is intended for use when determining whether a
9478/// special member of a containing object is trivial, and thus does not ever
9479/// perform overload resolution for default constructors.
9480///
9481/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9482/// member that was most likely to be intended to be trivial, if any.
9483///
9484/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9485/// determine whether the special member is trivial.
9487 Sema::CXXSpecialMember CSM, unsigned Quals,
9488 bool ConstRHS,
9490 CXXMethodDecl **Selected) {
9491 if (Selected)
9492 *Selected = nullptr;
9493
9494 switch (CSM) {
9495 case Sema::CXXInvalid:
9496 llvm_unreachable("not a special member");
9497
9499 // C++11 [class.ctor]p5:
9500 // A default constructor is trivial if:
9501 // - all the [direct subobjects] have trivial default constructors
9502 //
9503 // Note, no overload resolution is performed in this case.
9505 return true;
9506
9507 if (Selected) {
9508 // If there's a default constructor which could have been trivial, dig it
9509 // out. Otherwise, if there's any user-provided default constructor, point
9510 // to that as an example of why there's not a trivial one.
9511 CXXConstructorDecl *DefCtor = nullptr;
9514 for (auto *CI : RD->ctors()) {
9515 if (!CI->isDefaultConstructor())
9516 continue;
9517 DefCtor = CI;
9518 if (!DefCtor->isUserProvided())
9519 break;
9520 }
9521
9522 *Selected = DefCtor;
9523 }
9524
9525 return false;
9526
9528 // C++11 [class.dtor]p5:
9529 // A destructor is trivial if:
9530 // - all the direct [subobjects] have trivial destructors
9531 if (RD->hasTrivialDestructor() ||
9534 return true;
9535
9536 if (Selected) {
9537 if (RD->needsImplicitDestructor())
9539 *Selected = RD->getDestructor();
9540 }
9541
9542 return false;
9543
9545 // C++11 [class.copy]p12:
9546 // A copy constructor is trivial if:
9547 // - the constructor selected to copy each direct [subobject] is trivial
9548 if (RD->hasTrivialCopyConstructor() ||
9551 if (Quals == Qualifiers::Const)
9552 // We must either select the trivial copy constructor or reach an
9553 // ambiguity; no need to actually perform overload resolution.
9554 return true;
9555 } else if (!Selected) {
9556 return false;
9557 }
9558 // In C++98, we are not supposed to perform overload resolution here, but we
9559 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9560 // cases like B as having a non-trivial copy constructor:
9561 // struct A { template<typename T> A(T&); };
9562 // struct B { mutable A a; };
9563 goto NeedOverloadResolution;
9564
9566 // C++11 [class.copy]p25:
9567 // A copy assignment operator is trivial if:
9568 // - the assignment operator selected to copy each direct [subobject] is
9569 // trivial
9570 if (RD->hasTrivialCopyAssignment()) {
9571 if (Quals == Qualifiers::Const)
9572 return true;
9573 } else if (!Selected) {
9574 return false;
9575 }
9576 // In C++98, we are not supposed to perform overload resolution here, but we
9577 // treat that as a language defect.
9578 goto NeedOverloadResolution;
9579
9582 NeedOverloadResolution:
9584 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9585
9586 // The standard doesn't describe how to behave if the lookup is ambiguous.
9587 // We treat it as not making the member non-trivial, just like the standard
9588 // mandates for the default constructor. This should rarely matter, because
9589 // the member will also be deleted.
9591 return true;
9592
9593 if (!SMOR.getMethod()) {
9594 assert(SMOR.getKind() ==
9596 return false;
9597 }
9598
9599 // We deliberately don't check if we found a deleted special member. We're
9600 // not supposed to!
9601 if (Selected)
9602 *Selected = SMOR.getMethod();
9603
9604 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9606 return SMOR.getMethod()->isTrivialForCall();
9607 return SMOR.getMethod()->isTrivial();
9608 }
9609
9610 llvm_unreachable("unknown special method kind");
9611}
9612
9614 for (auto *CI : RD->ctors())
9615 if (!CI->isImplicit())
9616 return CI;
9617
9618 // Look for constructor templates.
9620 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9621 if (CXXConstructorDecl *CD =
9622 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9623 return CD;
9624 }
9625
9626 return nullptr;
9627}
9628
9629/// The kind of subobject we are checking for triviality. The values of this
9630/// enumeration are used in diagnostics.
9632 /// The subobject is a base class.
9634 /// The subobject is a non-static data member.
9636 /// The object is actually the complete object.
9639
9640/// Check whether the special member selected for a given type would be trivial.
9642 QualType SubType, bool ConstRHS,
9645 Sema::TrivialABIHandling TAH, bool Diagnose) {
9646 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9647 if (!SubRD)
9648 return true;
9649
9650 CXXMethodDecl *Selected;
9651 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9652 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9653 return true;
9654
9655 if (Diagnose) {
9656 if (ConstRHS)
9657 SubType.addConst();
9658
9659 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9660 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9661 << Kind << SubType.getUnqualifiedType();
9663 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9664 } else if (!Selected)
9665 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9666 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9667 else if (Selected->isUserProvided()) {
9668 if (Kind == TSK_CompleteObject)
9669 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9670 << Kind << SubType.getUnqualifiedType() << CSM;
9671 else {
9672 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9673 << Kind << SubType.getUnqualifiedType() << CSM;
9674 S.Diag(Selected->getLocation(), diag::note_declared_at);
9675 }
9676 } else {
9677 if (Kind != TSK_CompleteObject)
9678 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9679 << Kind << SubType.getUnqualifiedType() << CSM;
9680
9681 // Explain why the defaulted or deleted special member isn't trivial.
9683 Diagnose);
9684 }
9685 }
9686
9687 return false;
9688}
9689
9690/// Check whether the members of a class type allow a special member to be
9691/// trivial.
9694 bool ConstArg,
9696 bool Diagnose) {
9697 for (const auto *FI : RD->fields()) {
9698 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9699 continue;
9700
9701 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9702
9703 // Pretend anonymous struct or union members are members of this class.
9704 if (FI->isAnonymousStructOrUnion()) {
9705 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9706 CSM, ConstArg, TAH, Diagnose))
9707 return false;
9708 continue;
9709 }
9710
9711 // C++11 [class.ctor]p5:
9712 // A default constructor is trivial if [...]
9713 // -- no non-static data member of its class has a
9714 // brace-or-equal-initializer
9715 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9716 if (Diagnose)
9717 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9718 << FI;
9719 return false;
9720 }
9721
9722 // Objective C ARC 4.3.5:
9723 // [...] nontrivally ownership-qualified types are [...] not trivially
9724 // default constructible, copy constructible, move constructible, copy
9725 // assignable, move assignable, or destructible [...]
9726 if (FieldType.hasNonTrivialObjCLifetime()) {
9727 if (Diagnose)
9728 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9729 << RD << FieldType.getObjCLifetime();
9730 return false;
9731 }
9732
9733 bool ConstRHS = ConstArg && !FI->isMutable();
9734 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9735 CSM, TSK_Field, TAH, Diagnose))
9736 return false;
9737 }
9738
9739 return true;
9740}
9741
9742/// Diagnose why the specified class does not have a trivial special member of
9743/// the given kind.
9745 QualType Ty = Context.getRecordType(RD);
9746
9747 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9748 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9749 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9750 /*Diagnose*/true);
9751}
9752
9753/// Determine whether a defaulted or deleted special member function is trivial,
9754/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9755/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9757 TrivialABIHandling TAH, bool Diagnose) {
9758 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9759
9760 CXXRecordDecl *RD = MD->getParent();
9761
9762 bool ConstArg = false;
9763
9764 // C++11 [class.copy]p12, p25: [DR1593]
9765 // A [special member] is trivial if [...] its parameter-type-list is
9766 // equivalent to the parameter-type-list of an implicit declaration [...]
9767 switch (CSM) {
9768 case CXXDefaultConstructor:
9769 case CXXDestructor:
9770 // Trivial default constructors and destructors cannot have parameters.
9771 break;
9772
9773 case CXXCopyConstructor:
9774 case CXXCopyAssignment: {
9775 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9776 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9777
9778 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
9779 // if they are not user-provided and their parameter-type-list is equivalent
9780 // to the parameter-type-list of an implicit declaration. This maintains the
9781 // behavior before dr2171 was implemented.
9782 //
9783 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
9784 // trivial, if they are not user-provided, regardless of the qualifiers on
9785 // the reference type.
9786 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
9787 LangOptions::ClangABI::Ver14;
9788 if (!RT ||
9790 ClangABICompat14)) {
9791 if (Diagnose)
9792 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9793 << Param0->getSourceRange() << Param0->getType()
9794 << Context.getLValueReferenceType(
9795 Context.getRecordType(RD).withConst());
9796 return false;
9797 }
9798
9799 ConstArg = RT->getPointeeType().isConstQualified();
9800 break;
9801 }
9802
9803 case CXXMoveConstructor:
9804 case CXXMoveAssignment: {
9805 // Trivial move operations always have non-cv-qualified parameters.
9806 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9807 const RValueReferenceType *RT =
9808 Param0->getType()->getAs<RValueReferenceType>();
9809 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9810 if (Diagnose)
9811 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9812 << Param0->getSourceRange() << Param0->getType()
9813 << Context.getRValueReferenceType(Context.getRecordType(RD));
9814 return false;
9815 }
9816 break;
9817 }
9818
9819 case CXXInvalid:
9820 llvm_unreachable("not a special member");
9821 }
9822
9823 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9824 if (Diagnose)
9826 diag::note_nontrivial_default_arg)
9828 return false;
9829 }
9830 if (MD->isVariadic()) {
9831 if (Diagnose)
9832 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9833 return false;
9834 }
9835
9836 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9837 // A copy/move [constructor or assignment operator] is trivial if
9838 // -- the [member] selected to copy/move each direct base class subobject
9839 // is trivial
9840 //
9841 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9842 // A [default constructor or destructor] is trivial if
9843 // -- all the direct base classes have trivial [default constructors or
9844 // destructors]
9845 for (const auto &BI : RD->bases())
9846 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9847 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9848 return false;
9849
9850 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9851 // A copy/move [constructor or assignment operator] for a class X is
9852 // trivial if
9853 // -- for each non-static data member of X that is of class type (or array
9854 // thereof), the constructor selected to copy/move that member is
9855 // trivial
9856 //
9857 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9858 // A [default constructor or destructor] is trivial if
9859 // -- for all of the non-static data members of its class that are of class
9860 // type (or array thereof), each such class has a trivial [default
9861 // constructor or destructor]
9862 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9863 return false;
9864
9865 // C++11 [class.dtor]p5:
9866 // A destructor is trivial if [...]
9867 // -- the destructor is not virtual
9868 if (CSM == CXXDestructor && MD->isVirtual()) {
9869 if (Diagnose)
9870 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9871 return false;
9872 }
9873
9874 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9875 // A [special member] for class X is trivial if [...]
9876 // -- class X has no virtual functions and no virtual base classes
9877 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9878 if (!Diagnose)
9879 return false;
9880
9881 if (RD->getNumVBases()) {
9882 // Check for virtual bases. We already know that the corresponding
9883 // member in all bases is trivial, so vbases must all be direct.
9884 CXXBaseSpecifier &BS = *RD->vbases_begin();
9885 assert(BS.isVirtual());
9886 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9887 return false;
9888 }
9889
9890 // Must have a virtual method.
9891 for (const auto *MI : RD->methods()) {
9892 if (MI->isVirtual()) {
9893 SourceLocation MLoc = MI->getBeginLoc();
9894 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9895 return false;
9896 }
9897 }
9898
9899 llvm_unreachable("dynamic class with no vbases and no virtual functions");
9900 }
9901
9902 // Looks like it's trivial!
9903 return true;
9904}
9905
9906namespace {
9907struct FindHiddenVirtualMethod {
9908 Sema *S;
9909 CXXMethodDecl *Method;
9910 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9911 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9912
9913private:
9914 /// Check whether any most overridden method from MD in Methods
9915 static bool CheckMostOverridenMethods(
9916 const CXXMethodDecl *MD,
9917 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9918 if (MD->size_overridden_methods() == 0)
9919 return Methods.count(MD->getCanonicalDecl());
9920 for (const CXXMethodDecl *O : MD->overridden_methods())
9921 if (CheckMostOverridenMethods(O, Methods))
9922 return true;
9923 return false;
9924 }
9925
9926public:
9927 /// Member lookup function that determines whether a given C++
9928 /// method overloads virtual methods in a base class without overriding any,
9929 /// to be used with CXXRecordDecl::lookupInBases().
9930 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9931 RecordDecl *BaseRecord =
9932 Specifier->getType()->castAs<RecordType>()->getDecl();
9933
9934 DeclarationName Name = Method->getDeclName();
9935 assert(Name.getNameKind() == DeclarationName::Identifier);
9936
9937 bool foundSameNameMethod = false;
9938 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9939 for (Path.Decls = BaseRecord->lookup(Name).begin();
9940 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9941 NamedDecl *D = *Path.Decls;
9942 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9943 MD = MD->getCanonicalDecl();
9944 foundSameNameMethod = true;
9945 // Interested only in hidden virtual methods.
9946 if (!MD->isVirtual())
9947 continue;
9948 // If the method we are checking overrides a method from its base
9949 // don't warn about the other overloaded methods. Clang deviates from
9950 // GCC by only diagnosing overloads of inherited virtual functions that
9951 // do not override any other virtual functions in the base. GCC's
9952 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9953 // function from a base class. These cases may be better served by a
9954 // warning (not specific to virtual functions) on call sites when the
9955 // call would select a different function from the base class, were it
9956 // visible.
9957 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9958 if (!S->IsOverload(Method, MD, false))
9959 return true;
9960 // Collect the overload only if its hidden.
9961 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9962 overloadedMethods.push_back(MD);
9963 }
9964 }
9965
9966 if (foundSameNameMethod)
9967 OverloadedMethods.append(overloadedMethods.begin(),
9968 overloadedMethods.end());
9969 return foundSameNameMethod;
9970 }
9971};
9972} // end anonymous namespace
9973
9974/// Add the most overridden methods from MD to Methods
9976 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9977 if (MD->size_overridden_methods() == 0)
9978 Methods.insert(MD->getCanonicalDecl());
9979 else
9980 for (const CXXMethodDecl *O : MD->overridden_methods())
9981 AddMostOverridenMethods(O, Methods);
9982}
9983
9984/// Check if a method overloads virtual methods in a base class without
9985/// overriding any.
9987 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9988 if (!MD->getDeclName().isIdentifier())
9989 return;
9990
9991 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9992 /*bool RecordPaths=*/false,
9993 /*bool DetectVirtual=*/false);
9994 FindHiddenVirtualMethod FHVM;
9995 FHVM.Method = MD;
9996 FHVM.S = this;
9997
9998 // Keep the base methods that were overridden or introduced in the subclass
9999 // by 'using' in a set. A base method not in this set is hidden.
10000 CXXRecordDecl *DC = MD->getParent();
10002 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10003 NamedDecl *ND = *I;
10004 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10005 ND = shad->getTargetDecl();
10006 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10007 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10008 }
10009
10010 if (DC->lookupInBases(FHVM, Paths))
10011 OverloadedMethods = FHVM.OverloadedMethods;
10012}
10013
10015 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10016 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10017 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10018 PartialDiagnostic PD = PDiag(
10019 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10020 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10021 Diag(overloadedMD->getLocation(), PD);
10022 }
10023}
10024
10025/// Diagnose methods which overload virtual methods in a base class
10026/// without overriding any.
10028 if (MD->isInvalidDecl())
10029 return;
10030
10031 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10032 return;
10033
10034 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10035 FindHiddenVirtualMethods(MD, OverloadedMethods);
10036 if (!OverloadedMethods.empty()) {
10037 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10038 << MD << (OverloadedMethods.size() > 1);
10039
10040 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10041 }
10042}
10043
10045 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10046 // No diagnostics if this is a template instantiation.
10048 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10049 diag::ext_cannot_use_trivial_abi) << &RD;
10050 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10051 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10052 }
10053 RD.dropAttr<TrivialABIAttr>();
10054 };
10055
10056 // Ill-formed if the copy and move constructors are deleted.
10057 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10058 // If the type is dependent, then assume it might have
10059 // implicit copy or move ctor because we won't know yet at this point.
10060 if (RD.isDependentType())
10061 return true;
10064 return true;
10067 return true;
10068 for (const CXXConstructorDecl *CD : RD.ctors())
10069 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10070 return true;
10071 return false;
10072 };
10073
10074 if (!HasNonDeletedCopyOrMoveConstructor()) {
10075 PrintDiagAndRemoveAttr(0);
10076 return;
10077 }
10078
10079 // Ill-formed if the struct has virtual functions.
10080 if (RD.isPolymorphic()) {
10081 PrintDiagAndRemoveAttr(1);
10082 return;
10083 }
10084
10085 for (const auto &B : RD.bases()) {
10086 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10087 // virtual base.
10088 if (!B.getType()->isDependentType() &&
10089 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10090 PrintDiagAndRemoveAttr(2);
10091 return;
10092 }
10093
10094 if (B.isVirtual()) {
10095 PrintDiagAndRemoveAttr(3);
10096 return;
10097 }
10098 }
10099
10100 for (const auto *FD : RD.fields()) {
10101 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10102 // non-trivial for the purpose of calls.
10103 QualType FT = FD->getType();
10105 PrintDiagAndRemoveAttr(4);
10106 return;
10107 }
10108
10109 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10110 if (!RT->isDependentType() &&
10111 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10112 PrintDiagAndRemoveAttr(5);
10113 return;
10114 }
10115 }
10116}
10117
10120 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10121 if (!TagDecl)
10122 return;
10123
10124 AdjustDeclIfTemplate(TagDecl);
10125
10126 for (const ParsedAttr &AL : AttrList) {
10127 if (AL.getKind() != ParsedAttr::AT_Visibility)
10128 continue;
10129 AL.setInvalid();
10130 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10131 }
10132
10133 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10134 // strict aliasing violation!
10135 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10136 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10137
10138 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10139}
10140
10141/// Find the equality comparison functions that should be implicitly declared
10142/// in a given class definition, per C++2a [class.compare.default]p3.
10144 ASTContext &Ctx, CXXRecordDecl *RD,
10146 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10147 if (!RD->lookup(EqEq).empty())
10148 // Member operator== explicitly declared: no implicit operator==s.
10149 return;
10150
10151 // Traverse friends looking for an '==' or a '<=>'.
10152 for (FriendDecl *Friend : RD->friends()) {
10153 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10154 if (!FD) continue;
10155
10156 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10157 // Friend operator== explicitly declared: no implicit operator==s.
10158 Spaceships.clear();
10159 return;
10160 }
10161
10162 if (FD->getOverloadedOperator() == OO_Spaceship &&
10164 Spaceships.push_back(FD);
10165 }
10166
10167 // Look for members named 'operator<=>'.
10168 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10169 for (NamedDecl *ND : RD->lookup(Cmp)) {
10170 // Note that we could find a non-function here (either a function template
10171 // or a using-declaration). Neither case results in an implicit
10172 // 'operator=='.
10173 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10174 if (FD->isExplicitlyDefaulted())
10175 Spaceships.push_back(FD);
10176 }
10177}
10178
10179/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10180/// special functions, such as the default constructor, copy
10181/// constructor, or destructor, to the given C++ class (C++
10182/// [special]p1). This routine can only be executed just before the
10183/// definition of the class is complete.
10185 // Don't add implicit special members to templated classes.
10186 // FIXME: This means unqualified lookups for 'operator=' within a class
10187 // template don't work properly.
10188 if (!ClassDecl->isDependentType()) {
10189 if (ClassDecl->needsImplicitDefaultConstructor()) {
10190 ++getASTContext().NumImplicitDefaultConstructors;
10191
10192 if (ClassDecl->hasInheritedConstructor())
10193 DeclareImplicitDefaultConstructor(ClassDecl);
10194 }
10195
10196 if (ClassDecl->needsImplicitCopyConstructor()) {
10197 ++getASTContext().NumImplicitCopyConstructors;
10198
10199 // If the properties or semantics of the copy constructor couldn't be
10200 // determined while the class was being declared, force a declaration
10201 // of it now.
10203 ClassDecl->hasInheritedConstructor())
10204 DeclareImplicitCopyConstructor(ClassDecl);
10205 // For the MS ABI we need to know whether the copy ctor is deleted. A
10206 // prerequisite for deleting the implicit copy ctor is that the class has
10207 // a move ctor or move assignment that is either user-declared or whose
10208 // semantics are inherited from a subobject. FIXME: We should provide a
10209 // more direct way for CodeGen to ask whether the constructor was deleted.
10210 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10211 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10213 ClassDecl->hasUserDeclaredMoveAssignment() ||
10215 DeclareImplicitCopyConstructor(ClassDecl);
10216 }
10217
10218 if (getLangOpts().CPlusPlus11 &&
10219 ClassDecl->needsImplicitMoveConstructor()) {
10220 ++getASTContext().NumImplicitMoveConstructors;
10221
10223 ClassDecl->hasInheritedConstructor())
10224 DeclareImplicitMoveConstructor(ClassDecl);
10225 }
10226
10227 if (ClassDecl->needsImplicitCopyAssignment()) {
10228 ++getASTContext().NumImplicitCopyAssignmentOperators;
10229
10230 // If we have a dynamic class, then the copy assignment operator may be
10231 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10232 // it shows up in the right place in the vtable and that we diagnose
10233 // problems with the implicit exception specification.
10234 if (ClassDecl->isDynamicClass() ||
10236 ClassDecl->hasInheritedAssignment())
10237 DeclareImplicitCopyAssignment(ClassDecl);
10238 }
10239
10240 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10241 ++getASTContext().NumImplicitMoveAssignmentOperators;
10242
10243 // Likewise for the move assignment operator.
10244 if (ClassDecl->isDynamicClass() ||
10246 ClassDecl->hasInheritedAssignment())
10247 DeclareImplicitMoveAssignment(ClassDecl);
10248 }
10249
10250 if (ClassDecl->needsImplicitDestructor()) {
10251 ++getASTContext().NumImplicitDestructors;
10252
10253 // If we have a dynamic class, then the destructor may be virtual, so we
10254 // have to declare the destructor immediately. This ensures that, e.g., it
10255 // shows up in the right place in the vtable and that we diagnose problems
10256 // with the implicit exception specification.
10257 if (ClassDecl->isDynamicClass() ||
10259 DeclareImplicitDestructor(ClassDecl);
10260 }
10261 }
10262
10263 // C++2a [class.compare.default]p3:
10264 // If the member-specification does not explicitly declare any member or
10265 // friend named operator==, an == operator function is declared implicitly
10266 // for each defaulted three-way comparison operator function defined in
10267 // the member-specification
10268 // FIXME: Consider doing this lazily.
10269 // We do this during the initial parse for a class template, not during
10270 // instantiation, so that we can handle unqualified lookups for 'operator=='
10271 // when parsing the template.
10272 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10273 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10275 DefaultedSpaceships);
10276 for (auto *FD : DefaultedSpaceships)
10277 DeclareImplicitEqualityComparison(ClassDecl, FD);
10278 }
10279}
10280
10281unsigned
10283 llvm::function_ref<Scope *()> EnterScope) {
10284 if (!D)
10285 return 0;
10286 AdjustDeclIfTemplate(D);
10287
10288 // In order to get name lookup right, reenter template scopes in order from
10289 // outermost to innermost.
10291 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10292
10293 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10294 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10295 ParameterLists.push_back(DD->getTemplateParameterList(i));
10296
10297 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10298 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10299 ParameterLists.push_back(FTD->getTemplateParameters());
10300 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10301 LookupDC = VD->getDeclContext();
10302
10304 ParameterLists.push_back(VTD->getTemplateParameters());
10305 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10306 ParameterLists.push_back(PSD->getTemplateParameters());
10307 }
10308 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10309 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10310 ParameterLists.push_back(TD->getTemplateParameterList(i));
10311
10312 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10314 ParameterLists.push_back(CTD->getTemplateParameters());
10315 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10316 ParameterLists.push_back(PSD->getTemplateParameters());
10317 }
10318 }
10319 // FIXME: Alias declarations and concepts.
10320
10321 unsigned Count = 0;
10322 Scope *InnermostTemplateScope = nullptr;
10323 for (TemplateParameterList *Params : ParameterLists) {
10324 // Ignore explicit specializations; they don't contribute to the template
10325 // depth.
10326 if (Params->size() == 0)
10327 continue;
10328
10329 InnermostTemplateScope = EnterScope();
10330 for (NamedDecl *Param : *Params) {
10331 if (Param->getDeclName()) {
10332 InnermostTemplateScope->AddDecl(Param);
10333 IdResolver.AddDecl(Param);
10334 }
10335 }
10336 ++Count;
10337 }
10338
10339 // Associate the new template scopes with the corresponding entities.
10340 if (InnermostTemplateScope) {
10341 assert(LookupDC && "no enclosing DeclContext for template lookup");
10342 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10343 }
10344
10345 return Count;
10346}
10347
10349 if (!RecordD) return;
10350 AdjustDeclIfTemplate(RecordD);
10351 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10352 PushDeclContext(S, Record);
10353}
10354
10356 if (!RecordD) return;
10357 PopDeclContext();
10358}
10359
10360/// This is used to implement the constant expression evaluation part of the
10361/// attribute enable_if extension. There is nothing in standard C++ which would
10362/// require reentering parameters.
10364 if (!Param)
10365 return;
10366
10367 S->AddDecl(Param);
10368 if (Param->getDeclName())
10369 IdResolver.AddDecl(Param);
10370}
10371
10372/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10373/// parsing a top-level (non-nested) C++ class, and we are now
10374/// parsing those parts of the given Method declaration that could
10375/// not be parsed earlier (C++ [class.mem]p2), such as default
10376/// arguments. This action should enter the scope of the given
10377/// Method declaration as if we had just parsed the qualified method
10378/// name. However, it should not bring the parameters into scope;
10379/// that will be performed by ActOnDelayedCXXMethodParameter.
10382
10383/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10384/// C++ method declaration. We're (re-)introducing the given
10385/// function parameter into scope for use in parsing later parts of
10386/// the method declaration. For example, we could see an
10387/// ActOnParamDefaultArgument event for this parameter.
10389 if (!ParamD)
10390 return;
10391
10392 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10393
10394 S->AddDecl(Param);
10395 if (Param->getDeclName())
10396 IdResolver.AddDecl(Param);
10397}
10398
10399/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10400/// processing the delayed method declaration for Method. The method
10401/// declaration is now considered finished. There may be a separate
10402/// ActOnStartOfFunctionDef action later (not necessarily
10403/// immediately!) for this method, if it was also defined inside the
10404/// class body.
10406 if (!MethodD)
10407 return;
10408
10409 AdjustDeclIfTemplate(MethodD);
10410
10411 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10412
10413 // Now that we have our default arguments, check the constructor
10414 // again. It could produce additional diagnostics or affect whether
10415 // the class has implicitly-declared destructors, among other
10416 // things.
10417 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10418 CheckConstructor(Constructor);
10419
10420 // Check the default arguments, which we may have added.
10421 if (!Method->isInvalidDecl())
10422 CheckCXXDefaultArguments(Method);
10423}
10424
10425// Emit the given diagnostic for each non-address-space qualifier.
10426// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10427static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10429 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10430 bool DiagOccured = false;
10432 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10433 SourceLocation SL) {
10434 // This diagnostic should be emitted on any qualifier except an addr
10435 // space qualifier. However, forEachQualifier currently doesn't visit
10436 // addr space qualifiers, so there's no way to write this condition
10437 // right now; we just diagnose on everything.
10438 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10439 DiagOccured = true;
10440 });
10441 if (DiagOccured)
10442 D.setInvalidType();
10443 }
10444}
10445
10446/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10447/// the well-formedness of the constructor declarator @p D with type @p
10448/// R. If there are any errors in the declarator, this routine will
10449/// emit diagnostics and set the invalid bit to true. In any case, the type
10450/// will be updated to reflect a well-formed type for the constructor and
10451/// returned.
10453 StorageClass &SC) {
10454 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10455
10456 // C++ [class.ctor]p3:
10457 // A constructor shall not be virtual (10.3) or static (9.4). A
10458 // constructor can be invoked for a const, volatile or const
10459 // volatile object. A constructor shall not be declared const,
10460 // volatile, or const volatile (9.3.2).
10461 if (isVirtual) {
10462 if (!D.isInvalidType())
10463 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10464 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10466 D.setInvalidType();
10467 }
10468 if (SC == SC_Static) {
10469 if (!D.isInvalidType())
10470 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10471 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10473 D.setInvalidType();
10474 SC = SC_None;
10475 }
10476
10477 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10478 diagnoseIgnoredQualifiers(
10479 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10483 D.setInvalidType();
10484 }
10485
10486 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10487
10488 // C++0x [class.ctor]p4:
10489 // A constructor shall not be declared with a ref-qualifier.
10491 if (FTI.hasRefQualifier()) {
10492 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10495 D.setInvalidType();
10496 }
10497
10498 // Rebuild the function type "R" without any type qualifiers (in
10499 // case any of the errors above fired) and with "void" as the
10500 // return type, since constructors don't have return types.
10501 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10502 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10503 return R;
10504
10506 EPI.TypeQuals = Qualifiers();
10507 EPI.RefQualifier = RQ_None;
10508
10509 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10510}
10511
10512/// CheckConstructor - Checks a fully-formed constructor for
10513/// well-formedness, issuing any diagnostics required. Returns true if
10514/// the constructor declarator is invalid.
10516 CXXRecordDecl *ClassDecl
10517 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10518 if (!ClassDecl)
10519 return Constructor->setInvalidDecl();
10520
10521 // C++ [class.copy]p3:
10522 // A declaration of a constructor for a class X is ill-formed if
10523 // its first parameter is of type (optionally cv-qualified) X and
10524 // either there are no other parameters or else all other
10525 // parameters have default arguments.
10526 if (!Constructor->isInvalidDecl() &&
10527 Constructor->hasOneParamOrDefaultArgs() &&
10528 Constructor->getTemplateSpecializationKind() !=
10530 QualType ParamType = Constructor->getParamDecl(0)->getType();
10531 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10532 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10533 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10534 const char *ConstRef
10535 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10536 : " const &";
10537 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10538 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10539
10540 // FIXME: Rather that making the constructor invalid, we should endeavor
10541 // to fix the type.
10542 Constructor->setInvalidDecl();
10543 }
10544 }
10545}
10546
10547/// CheckDestructor - Checks a fully-formed destructor definition for
10548/// well-formedness, issuing any diagnostics required. Returns true
10549/// on error.
10551 CXXRecordDecl *RD = Destructor->getParent();
10552
10553 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10554 SourceLocation Loc;
10555
10556 if (!Destructor->isImplicit())
10557 Loc = Destructor->getLocation();
10558 else
10559 Loc = RD->getLocation();
10560
10561 // If we have a virtual destructor, look up the deallocation function
10562 if (FunctionDecl *OperatorDelete =
10563 FindDeallocationFunctionForDestructor(Loc, RD)) {
10564 Expr *ThisArg = nullptr;
10565
10566 // If the notional 'delete this' expression requires a non-trivial
10567 // conversion from 'this' to the type of a destroying operator delete's
10568 // first parameter, perform that conversion now.
10569 if (OperatorDelete->isDestroyingOperatorDelete()) {
10570 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10571 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10572 // C++ [class.dtor]p13:
10573 // ... as if for the expression 'delete this' appearing in a
10574 // non-virtual destructor of the destructor's class.
10575 ContextRAII SwitchContext(*this, Destructor);
10576 ExprResult This =
10577 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10578 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10579 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10580 if (This.isInvalid()) {
10581 // FIXME: Register this as a context note so that it comes out
10582 // in the right order.
10583 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10584 return true;
10585 }
10586 ThisArg = This.get();
10587 }
10588 }
10589
10590 DiagnoseUseOfDecl(OperatorDelete, Loc);
10591 MarkFunctionReferenced(Loc, OperatorDelete);
10592 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10593 }
10594 }
10595
10596 return false;
10597}
10598
10599/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10600/// the well-formednes of the destructor declarator @p D with type @p
10601/// R. If there are any errors in the declarator, this routine will
10602/// emit diagnostics and set the declarator to invalid. Even if this happens,
10603/// will be updated to reflect a well-formed type for the destructor and
10604/// returned.
10606 StorageClass& SC) {
10607 // C++ [class.dtor]p1:
10608 // [...] A typedef-name that names a class is a class-name
10609 // (7.1.3); however, a typedef-name that names a class shall not
10610 // be used as the identifier in the declarator for a destructor
10611 // declaration.
10612 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10613 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10614 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10615 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10616 else if (const TemplateSpecializationType *TST =
10617 DeclaratorType->getAs<TemplateSpecializationType>())
10618 if (TST->isTypeAlias())
10619 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10620 << DeclaratorType << 1;
10621
10622 // C++ [class.dtor]p2:
10623 // A destructor is used to destroy objects of its class type. A
10624 // destructor takes no parameters, and no return type can be
10625 // specified for it (not even void). The address of a destructor
10626 // shall not be taken. A destructor shall not be static. A
10627 // destructor can be invoked for a const, volatile or const
10628 // volatile object. A destructor shall not be declared const,
10629 // volatile or const volatile (9.3.2).
10630 if (SC == SC_Static) {
10631 if (!D.isInvalidType())
10632 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10633 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10636
10637 SC = SC_None;
10638 }
10639 if (!D.isInvalidType()) {
10640 // Destructors don't have return types, but the parser will
10641 // happily parse something like:
10642 //
10643 // class X {
10644 // float ~X();
10645 // };
10646 //
10647 // The return type will be eliminated later.
10648 if (D.getDeclSpec().hasTypeSpecifier())
10649 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10652 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10653 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10659 D.setInvalidType();
10660 }
10661 }
10662
10663 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10664
10665 // C++0x [class.dtor]p2:
10666 // A destructor shall not be declared with a ref-qualifier.
10668 if (FTI.hasRefQualifier()) {
10669 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10672 D.setInvalidType();
10673 }
10674
10675 // Make sure we don't have any parameters.
10676 if (FTIHasNonVoidParameters(FTI)) {
10677 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10678
10679 // Delete the parameters.
10680 FTI.freeParams();
10681 D.setInvalidType();
10682 }
10683
10684 // Make sure the destructor isn't variadic.
10685 if (FTI.isVariadic) {
10686 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10687 D.setInvalidType();
10688 }
10689
10690 // Rebuild the function type "R" without any type qualifiers or
10691 // parameters (in case any of the errors above fired) and with
10692 // "void" as the return type, since destructors don't have return
10693 // types.
10694 if (!D.isInvalidType())
10695 return R;
10696
10697 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10699 EPI.Variadic = false;
10700 EPI.TypeQuals = Qualifiers();
10701 EPI.RefQualifier = RQ_None;
10702 return Context.getFunctionType(Context.VoidTy, None, EPI);
10703}
10704
10705static void extendLeft(SourceRange &R, SourceRange Before) {
10706 if (Before.isInvalid())
10707 return;
10708 R.setBegin(Before.getBegin());
10709 if (R.getEnd().isInvalid())
10710 R.setEnd(Before.getEnd());
10711}
10712
10713static void extendRight(SourceRange &R, SourceRange After) {
10714 if (After.isInvalid())
10715 return;
10716 if (R.getBegin().isInvalid())
10717 R.setBegin(After.getBegin());
10718 R.setEnd(After.getEnd());
10719}
10720
10721/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10722/// well-formednes of the conversion function declarator @p D with
10723/// type @p R. If there are any errors in the declarator, this routine
10724/// will emit diagnostics and return true. Otherwise, it will return
10725/// false. Either way, the type @p R will be updated to reflect a
10726/// well-formed type for the conversion operator.
10728 StorageClass& SC) {
10729 // C++ [class.conv.fct]p1:
10730 // Neither parameter types nor return type can be specified. The
10731 // type of a conversion function (8.3.5) is "function taking no
10732 // parameter returning conversion-type-id."
10733 if (SC == SC_Static) {
10734 if (!D.isInvalidType())
10735 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10737 << D.getName().getSourceRange();
10738 D.setInvalidType();
10739 SC = SC_None;
10740 }
10741
10742 TypeSourceInfo *ConvTSI = nullptr;
10743 QualType ConvType =
10744 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10745
10746 const DeclSpec &DS = D.getDeclSpec();
10747 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10748 // Conversion functions don't have return types, but the parser will
10749 // happily parse something like:
10750 //
10751 // class X {
10752 // float operator bool();
10753 // };
10754 //
10755 // The return type will be changed later anyway.
10756 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10759 D.setInvalidType();
10760 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10761 // It's also plausible that the user writes type qualifiers in the wrong
10762 // place, such as:
10763 // struct S { const operator int(); };
10764 // FIXME: we could provide a fixit to move the qualifiers onto the
10765 // conversion type.
10766 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10767 << SourceRange(D.getIdentifierLoc()) << 0;
10768 D.setInvalidType();
10769 }
10770
10771 const auto *Proto = R->castAs<FunctionProtoType>();
10772
10773 // Make sure we don't have any parameters.
10774 if (Proto->getNumParams() > 0) {
10775 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10776
10777 // Delete the parameters.
10779 D.setInvalidType();
10780 } else if (Proto->isVariadic()) {
10781 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10782 D.setInvalidType();
10783 }
10784
10785 // Diagnose "&operator bool()" and other such nonsense. This
10786 // is actually a gcc extension which we don't support.
10787 if (Proto->getReturnType() != ConvType) {
10788 bool NeedsTypedef = false;
10789 SourceRange Before, After;
10790
10791 // Walk the chunks and extract information on them for our diagnostic.
10792 bool PastFunctionChunk = false;
10793 for (auto &Chunk : D.type_objects()) {
10794 switch (Chunk.Kind) {
10796 if (!PastFunctionChunk) {
10797 if (Chunk.Fun.HasTrailingReturnType) {
10798 TypeSourceInfo *TRT = nullptr;
10799 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10800 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10801 }
10802 PastFunctionChunk = true;
10803 break;
10804 }
10805 LLVM_FALLTHROUGH;
10807 NeedsTypedef = true;
10808 extendRight(After, Chunk.getSourceRange());
10809 break;
10810
10816 extendLeft(Before, Chunk.getSourceRange());
10817 break;
10818
10820 extendLeft(Before, Chunk.Loc);
10821 extendRight(After, Chunk.EndLoc);
10822 break;
10823 }
10824 }
10825
10826 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10827 After.isValid() ? After.getBegin() :
10828 D.getIdentifierLoc();
10829 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10830 DB << Before << After;
10831
10832 if (!NeedsTypedef) {
10833 DB << /*don't need a typedef*/0;
10834
10835 // If we can provide a correct fix-it hint, do so.
10836 if (After.isInvalid() && ConvTSI) {
10837 SourceLocation InsertLoc =
10838 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10839 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10841 InsertLoc, CharSourceRange::getTokenRange(Before))
10842 << FixItHint::CreateRemoval(Before);
10843 }
10844 } else if (!Proto->getReturnType()->isDependentType()) {
10845 DB << /*typedef*/1 << Proto->getReturnType();
10846 } else if (getLangOpts().CPlusPlus11) {
10847 DB << /*alias template*/2 << Proto->getReturnType();
10848 } else {
10849 DB << /*might not be fixable*/3;
10850 }
10851
10852 // Recover by incorporating the other type chunks into the result type.
10853 // Note, this does *not* change the name of the function. This is compatible
10854 // with the GCC extension:
10855 // struct S { &operator int(); } s;
10856 // int &r = s.operator int(); // ok in GCC
10857 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10858 ConvType = Proto->getReturnType();
10859 }
10860
10861 // C++ [class.conv.fct]p4:
10862 // The conversion-type-id shall not represent a function type nor
10863 // an array type.
10864 if (ConvType->isArrayType()) {
10865 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10866 ConvType = Context.getPointerType(ConvType);
10867 D.setInvalidType();
10868 } else if (ConvType->isFunctionType()) {
10869 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10870 ConvType = Context.getPointerType(ConvType);
10871 D.setInvalidType();
10872 }
10873
10874 // Rebuild the function type "R" without any parameters (in case any
10875 // of the errors above fired) and with the conversion type as the
10876 // return type.
10877 if (D.isInvalidType())
10878 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10879
10880 // C++0x explicit conversion operators.
10881 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10883 getLangOpts().CPlusPlus11
10884 ? diag::warn_cxx98_compat_explicit_conversion_functions
10885 : diag::ext_explicit_conversion_functions)
10887}
10888
10889/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10890/// the declaration of the given C++ conversion function. This routine
10891/// is responsible for recording the conversion function in the C++
10892/// class, if possible.
10894 assert(Conversion && "Expected to receive a conversion function declaration");
10895
10896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10897
10898 // Make sure we aren't redeclaring the conversion function.
10899 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10900 // C++ [class.conv.fct]p1:
10901 // [...] A conversion function is never used to convert a
10902 // (possibly cv-qualified) object to the (possibly cv-qualified)
10903 // same object type (or a reference to it), to a (possibly
10904 // cv-qualified) base class of that type (or a reference to it),
10905 // or to (possibly cv-qualified) void.
10906 QualType ClassType
10907 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10908 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10909 ConvType = ConvTypeRef->getPointeeType();
10910 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10912 /* Suppress diagnostics for instantiations. */;
10913 else if (Conversion->size_overridden_methods() != 0)
10914 /* Suppress diagnostics for overriding virtual function in a base class. */;
10915 else if (ConvType->isRecordType()) {
10916 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10917 if (ConvType == ClassType)
10918 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10919 << ClassType;
10920 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10921 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10922 << ClassType << ConvType;
10923 } else if (ConvType->isVoidType()) {
10924 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10925 << ClassType << ConvType;
10926 }
10927
10928 if (FunctionTemplateDecl *ConversionTemplate
10929 = Conversion->getDescribedFunctionTemplate())
10930 return ConversionTemplate;
10931
10932 return Conversion;
10933}
10934
10935namespace {
10936/// Utility class to accumulate and print a diagnostic listing the invalid
10937/// specifier(s) on a declaration.
10938struct BadSpecifierDiagnoser {
10939 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10940 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10941 ~BadSpecifierDiagnoser() {
10942 Diagnostic << Specifiers;
10943 }
10944
10945 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10946 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10947 }
10948 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10949 return check(SpecLoc,
10951 }
10952 void check(SourceLocation SpecLoc, const char *Spec) {
10953 if (SpecLoc.isInvalid()) return;
10954 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10955 if (!Specifiers.empty()) Specifiers += " ";
10956 Specifiers += Spec;
10957 }
10958
10959 Sema &S;
10961 std::string Specifiers;
10962};
10963}
10964
10965/// Check the validity of a declarator that we parsed for a deduction-guide.
10966/// These aren't actually declarators in the grammar, so we need to check that
10967/// the user didn't specify any pieces that are not part of the deduction-guide
10968/// grammar.
10970 StorageClass &SC) {
10971 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10972 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10973 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10974
10975 // C++ [temp.deduct.guide]p3:
10976 // A deduction-gide shall be declared in the same scope as the
10977 // corresponding class template.
10978 if (!CurContext->getRedeclContext()->Equals(
10979 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10980 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10981 << GuidedTemplateDecl;
10982 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10983 }
10984
10985 auto &DS = D.getMutableDeclSpec();
10986 // We leave 'friend' and 'virtual' to be rejected in the normal way.
10987 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10988 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10989 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10990 BadSpecifierDiagnoser Diagnoser(
10991 *this, D.getIdentifierLoc(),
10992 diag::err_deduction_guide_invalid_specifier);
10993
10994 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10995 DS.ClearStorageClassSpecs();
10996 SC = SC_None;
10997
10998 // 'explicit' is permitted.
10999 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11000 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11001 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11002 DS.ClearConstexprSpec();
11003
11004 Diagnoser.check(DS.getConstSpecLoc(), "const");
11005 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11006 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11007 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11008 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11009 DS.ClearTypeQualifiers();
11010
11011 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11012 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11013 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11014 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11015 DS.ClearTypeSpecType();
11016 }
11017
11018 if (D.isInvalidType())
11019 return;
11020
11021 // Check the declarator is simple enough.
11022 bool FoundFunction = false;
11023 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11024 if (Chunk.Kind == DeclaratorChunk::Paren)
11025 continue;
11026 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11028 diag::err_deduction_guide_with_complex_decl)
11029 << D.getSourceRange();
11030 break;
11031 }
11032 if (!Chunk.Fun.hasTrailingReturnType()) {
11033 Diag(D.getName().getBeginLoc(),
11034 diag::err_deduction_guide_no_trailing_return_type);
11035 break;
11036 }
11037
11038 // Check that the return type is written as a specialization of
11039 // the template specified as the deduction-guide's name.
11040 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11041 TypeSourceInfo *TSI = nullptr;
11042 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11043 assert(TSI && "deduction guide has valid type but invalid return type?");
11044 bool AcceptableReturnType = false;
11045 bool MightInstantiateToSpecialization = false;
11046 if (auto RetTST =
11048 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11049 bool TemplateMatches =
11050 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11051 // FIXME: We should consider other template kinds (using, qualified),
11052 // otherwise we will emit bogus diagnostics.
11053 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11054 AcceptableReturnType = true;
11055 else {
11056 // This could still instantiate to the right type, unless we know it
11057 // names the wrong class template.
11058 auto *TD = SpecifiedName.getAsTemplateDecl();
11059 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11060 !TemplateMatches);
11061 }
11062 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11063 MightInstantiateToSpecialization = true;
11064 }
11065
11066 if (!AcceptableReturnType) {
11067 Diag(TSI->getTypeLoc().getBeginLoc(),
11068 diag::err_deduction_guide_bad_trailing_return_type)
11069 << GuidedTemplate << TSI->getType()
11070 << MightInstantiateToSpecialization
11071 << TSI->getTypeLoc().getSourceRange();
11072 }
11073
11074 // Keep going to check that we don't have any inner declarator pieces (we
11075 // could still have a function returning a pointer to a function).
11076 FoundFunction = true;
11077 }
11078
11079 if (D.isFunctionDefinition())
11080 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11081}
11082
11083//===----------------------------------------------------------------------===//
11084// Namespace Handling
11085//===----------------------------------------------------------------------===//
11086
11087/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11088/// reopened.
11090 SourceLocation Loc,
11091 IdentifierInfo *II, bool *IsInline,
11092 NamespaceDecl *PrevNS) {
11093 assert(*IsInline != PrevNS->isInline());
11094
11095 // 'inline' must appear on the original definition, but not necessarily
11096 // on all extension definitions, so the note should point to the first
11097 // definition to avoid confusion.
11098 PrevNS = PrevNS->getFirstDecl();
11099
11100 if (PrevNS->isInline())
11101 // The user probably just forgot the 'inline', so suggest that it
11102 // be added back.
11103 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11104 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11105 else
11106 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11107
11108 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11109 *IsInline = PrevNS->isInline();
11110}
11111
11112/// ActOnStartNamespaceDef - This is called at the start of a namespace
11113/// definition.
11115 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11116 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11117 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11118 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11119 // For anonymous namespace, take the location of the left brace.
11120 SourceLocation Loc = II ? IdentLoc : LBrace;
11121 bool IsInline = InlineLoc.isValid();
11122 bool IsInvalid = false;
11123 bool IsStd = false;
11124 bool AddToKnown = false;
11125 Scope *DeclRegionScope = NamespcScope->getParent();
11126
11127 NamespaceDecl *PrevNS = nullptr;
11128 if (II) {
11129 // C++ [namespace.def]p2:
11130 // The identifier in an original-namespace-definition shall not
11131 // have been previously defined in the declarative region in
11132 // which the original-namespace-definition appears. The
11133 // identifier in an original-namespace-definition is the name of
11134 // the namespace. Subsequently in that declarative region, it is
11135 // treated as an original-namespace-name.
11136 //
11137 // Since namespace names are unique in their scope, and we don't
11138 // look through using directives, just look for any ordinary names
11139 // as if by qualified name lookup.
11140 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11141 ForExternalRedeclaration);
11142 LookupQualifiedName(R, CurContext->getRedeclContext());
11143 NamedDecl *PrevDecl =
11144 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11145 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11146
11147 if (PrevNS) {
11148 // This is an extended namespace definition.
11149 if (IsInline != PrevNS->isInline())
11150 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11151 &IsInline, PrevNS);
11152 } else if (PrevDecl) {
11153 // This is an invalid name redefinition.
11154 Diag(Loc, diag::err_redefinition_different_kind)
11155 << II;
11156 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11157 IsInvalid = true;
11158 // Continue on to push Namespc as current DeclContext and return it.
11159 } else if (II->isStr("std") &&
11160 CurContext->getRedeclContext()->isTranslationUnit()) {
11161 // This is the first "real" definition of the namespace "std", so update
11162 // our cache of the "std" namespace to point at this definition.
11163 PrevNS = getStdNamespace();
11164 IsStd = true;
11165 AddToKnown = !IsInline;
11166 } else {
11167 // We've seen this namespace for the first time.
11168 AddToKnown = !IsInline;
11169 }
11170 } else {
11171 // Anonymous namespaces.
11172
11173 // Determine whether the parent already has an anonymous namespace.
11174 DeclContext *Parent = CurContext->getRedeclContext();
11175 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11176 PrevNS = TU->getAnonymousNamespace();
11177 } else {
11179 PrevNS = ND->getAnonymousNamespace();
11180 }
11181
11182 if (PrevNS && IsInline != PrevNS->isInline())
11183 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11184 &IsInline, PrevNS);
11185 }
11186
11187 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11188 StartLoc, Loc, II, PrevNS);
11189 if (IsInvalid)
11190 Namespc->setInvalidDecl();
11191
11192 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11193 AddPragmaAttributes(DeclRegionScope, Namespc);
11194
11195 // FIXME: Should we be merging attributes?
11196 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11197 PushNamespaceVisibilityAttr(Attr, Loc);
11198
11199 if (IsStd)
11200 StdNamespace = Namespc;
11201 if (AddToKnown)
11202 KnownNamespaces[Namespc] = false;
11203
11204 if (II) {
11205 PushOnScopeChains(Namespc, DeclRegionScope);
11206 } else {
11207 // Link the anonymous namespace into its parent.
11208 DeclContext *Parent = CurContext->getRedeclContext();
11209 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11210 TU->setAnonymousNamespace(Namespc);
11211 } else {
11212 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11213 }
11214
11215 CurContext->addDecl(Namespc);
11216
11217 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11218 // behaves as if it were replaced by
11219 // namespace unique { /* empty body */ }
11220 // using namespace unique;
11221 // namespace unique { namespace-body }
11222 // where all occurrences of 'unique' in a translation unit are
11223 // replaced by the same identifier and this identifier differs
11224 // from all other identifiers in the entire program.
11225
11226 // We just create the namespace with an empty name and then add an
11227 // implicit using declaration, just like the standard suggests.
11228 //
11229 // CodeGen enforces the "universally unique" aspect by giving all
11230 // declarations semantically contained within an anonymous
11231 // namespace internal linkage.
11232
11233 if (!PrevNS) {
11234 UD = UsingDirectiveDecl::Create(Context, Parent,
11235 /* 'using' */ LBrace,
11236 /* 'namespace' */ SourceLocation(),
11237 /* qualifier */ NestedNameSpecifierLoc(),
11238 /* identifier */ SourceLocation(),
11239 Namespc,
11240 /* Ancestor */ Parent);
11241 UD->setImplicit();
11242 Parent->addDecl(UD);
11243 }
11244 }
11245
11246 ActOnDocumentableDecl(Namespc);
11247
11248 // Although we could have an invalid decl (i.e. the namespace name is a
11249 // redefinition), push it as current DeclContext and try to continue parsing.
11250 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11251 // for the namespace has the declarations that showed up in that particular
11252 // namespace definition.
11253 PushDeclContext(NamespcScope, Namespc);
11254 return Namespc;
11255}
11256
11257/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11258/// is a namespace alias, returns the namespace it points to.
11260 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11261 return AD->getNamespace();
11262 return dyn_cast_or_null<NamespaceDecl>(D);
11263}
11264
11265/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11266/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11268 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11269 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11270 Namespc->setRBraceLoc(RBrace);
11271 PopDeclContext();
11272 if (Namespc->hasAttr<VisibilityAttr>())
11273 PopPragmaVisibility(true, RBrace);
11274 // If this namespace contains an export-declaration, export it now.
11275 if (DeferredExportedNamespaces.erase(Namespc))
11276 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11277}
11278
11280 return cast_or_null<CXXRecordDecl>(
11281 StdBadAlloc.get(Context.getExternalSource()));
11282}
11283
11285 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11286}
11287
11289 return cast_or_null<NamespaceDecl>(
11290 StdNamespace.get(Context.getExternalSource()));
11291}
11292
11294 if (!StdExperimentalNamespaceCache) {
11295 if (auto Std = getStdNamespace()) {
11296 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11297 SourceLocation(), LookupNamespaceName);
11298 if (!LookupQualifiedName(Result, Std) ||
11299 !(StdExperimentalNamespaceCache =
11300 Result.getAsSingle<NamespaceDecl>()))
11301 Result.suppressDiagnostics();
11302 }
11303 }
11304 return StdExperimentalNamespaceCache;
11305}
11306
11307namespace {
11308
11309enum UnsupportedSTLSelect {
11310 USS_InvalidMember,
11311 USS_MissingMember,
11312 USS_NonTrivial,
11313 USS_Other
11314};
11315
11316struct InvalidSTLDiagnoser {
11317 Sema &S;
11318 SourceLocation Loc;
11319 QualType TyForDiags;
11320
11321 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11322 const VarDecl *VD = nullptr) {
11323 {
11324 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11325 << TyForDiags << ((int)Sel);
11326 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11327 assert(!Name.empty());
11328 D << Name;
11329 }
11330 }
11331 if (Sel == USS_InvalidMember) {
11332 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11333 << VD << VD->getSourceRange();
11334 }
11335 return QualType();
11336 }
11337};
11338} // namespace
11339
11341 SourceLocation Loc,
11343 assert(getLangOpts().CPlusPlus &&
11344 "Looking for comparison category type outside of C++.");
11345
11346 // Use an elaborated type for diagnostics which has a name containing the
11347 // prepended 'std' namespace but not any inline namespace names.
11348 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11349 auto *NNS =
11350 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11351 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11352 };
11353
11354 // Check if we've already successfully checked the comparison category type
11355 // before. If so, skip checking it again.
11356 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11357 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11358 // The only thing we need to check is that the type has a reachable
11359 // definition in the current context.
11360 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11361 return QualType();
11362
11363 return Info->getType();
11364 }
11365
11366 // If lookup failed
11367 if (!Info) {
11368 std::string NameForDiags = "std::";
11369 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11370 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11371 << NameForDiags << (int)Usage;
11372 return QualType();
11373 }
11374
11375 assert(Info->Kind == Kind);
11376 assert(Info->Record);
11377
11378 // Update the Record decl in case we encountered a forward declaration on our
11379 // first pass. FIXME: This is a bit of a hack.
11380 if (Info->Record->hasDefinition())
11381 Info->Record = Info->Record->getDefinition();
11382
11383 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11384 return QualType();
11385
11386 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11387
11388 if (!Info->Record->isTriviallyCopyable())
11389 return UnsupportedSTLError(USS_NonTrivial);
11390
11391 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11392 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11393 // Tolerate empty base classes.
11394 if (Base->isEmpty())
11395 continue;
11396 // Reject STL implementations which have at least one non-empty base.
11397 return UnsupportedSTLError();
11398 }
11399
11400 // Check that the STL has implemented the types using a single integer field.
11401 // This expectation allows better codegen for builtin operators. We require:
11402 // (1) The class has exactly one field.
11403 // (2) The field is an integral or enumeration type.
11404 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11405 if (std::distance(FIt, FEnd) != 1 ||
11406 !FIt->getType()->isIntegralOrEnumerationType()) {
11407 return UnsupportedSTLError();
11408 }
11409
11410 // Build each of the require values and store them in Info.
11411 for (ComparisonCategoryResult CCR :
11413 StringRef MemName = ComparisonCategories::getResultString(CCR);
11414 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11415
11416 if (!ValInfo)
11417 return UnsupportedSTLError(USS_MissingMember, MemName);
11418
11419 VarDecl *VD = ValInfo->VD;
11420 assert(VD && "should not be null!");
11421
11422 // Attempt to diagnose reasons why the STL definition of this type
11423 // might be foobar, including it failing to be a constant expression.
11424 // TODO Handle more ways the lookup or result can be invalid.
11425 if (!VD->isStaticDataMember() ||
11426 !VD->isUsableInConstantExpressions(Context))
11427 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11428
11429 // Attempt to evaluate the var decl as a constant expression and extract
11430 // the value of its first field as a ICE. If this fails, the STL
11431 // implementation is not supported.
11432 if (!ValInfo->hasValidIntValue())
11433 return UnsupportedSTLError();
11434
11435 MarkVariableReferenced(Loc, VD);
11436 }
11437
11438 // We've successfully built the required types and expressions. Update
11439 // the cache and return the newly cached value.
11440 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11441 return Info->getType();
11442}
11443
11444/// Retrieve the special "std" namespace, which may require us to
11445/// implicitly define the namespace.
11447 if (!StdNamespace) {
11448 // The "std" namespace has not yet been defined, so build one implicitly.
11449 StdNamespace = NamespaceDecl::Create(Context,
11450 Context.getTranslationUnitDecl(),
11451 /*Inline=*/false,
11453 &PP.getIdentifierTable().get("std"),
11454 /*PrevDecl=*/nullptr);
11455 getStdNamespace()->setImplicit(true);
11456 }
11457
11458 return getStdNamespace();
11459}
11460
11462 assert(getLangOpts().CPlusPlus &&
11463 "Looking for std::initializer_list outside of C++.");
11464
11465 // We're looking for implicit instantiations of
11466 // template <typename E> class std::initializer_list.
11467
11468 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11469 return false;
11470
11471 ClassTemplateDecl *Template = nullptr;
11472 const TemplateArgument *Arguments = nullptr;
11473
11474 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11475
11477 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11478 if (!Specialization)
11479 return false;
11480
11481 Template = Specialization->getSpecializedTemplate();
11482 Arguments = Specialization->getTemplateArgs().data();
11483 } else if (const TemplateSpecializationType *TST =
11485 Template = dyn_cast_or_null<ClassTemplateDecl>(
11486 TST->getTemplateName().getAsTemplateDecl());
11487 Arguments = TST->getArgs();
11488 }
11489 if (!Template)
11490 return false;
11491
11492 if (!StdInitializerList) {
11493 // Haven't recognized std::initializer_list yet, maybe this is it.
11494 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11495 if (TemplateClass->getIdentifier() !=
11496 &PP.getIdentifierTable().get("initializer_list") ||
11497 !getStdNamespace()->InEnclosingNamespaceSetOf(
11498 TemplateClass->getDeclContext()))
11499 return false;
11500 // This is a template called std::initializer_list, but is it the right
11501 // template?
11502 TemplateParameterList *Params = Template->getTemplateParameters();
11503 if (Params->getMinRequiredArguments() != 1)
11504 return false;
11505 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11506 return false;
11507
11508 // It's the right template.
11509 StdInitializerList = Template;
11510 }
11511
11512 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11513 return false;
11514
11515 // This is an instance of std::initializer_list. Find the argument type.
11516 if (Element)
11517 *Element = Arguments[0].getAsType();
11518 return true;
11519}
11520
11523 if (!Std) {
11524 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11525 return nullptr;
11526 }
11527
11528 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11530 if (!S.LookupQualifiedName(Result, Std)) {
11531 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11532 return nullptr;
11533 }
11534 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11535 if (!Template) {
11536 Result.suppressDiagnostics();
11537 // We found something weird. Complain about the first thing we found.
11538 NamedDecl *Found = *Result.begin();
11539 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11540 return nullptr;
11541 }
11542
11543 // We found some template called std::initializer_list. Now verify that it's
11544 // correct.
11545 TemplateParameterList *Params = Template->getTemplateParameters();
11546 if (Params->getMinRequiredArguments() != 1 ||
11547 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11548 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11549 return nullptr;
11550 }
11551
11552 return Template;
11553}
11554
11556 if (!StdInitializerList) {
11557 StdInitializerList = LookupStdInitializerList(*this, Loc);
11558 if (!StdInitializerList)
11559 return QualType();
11560 }
11561
11562 TemplateArgumentListInfo Args(Loc, Loc);
11564 Context.getTrivialTypeSourceInfo(Element,
11565 Loc)));
11566 return Context.getCanonicalType(
11567 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11568}
11569
11571 // C++ [dcl.init.list]p2:
11572 // A constructor is an initializer-list constructor if its first parameter
11573 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11574 // std::initializer_list<E> for some type E, and either there are no other
11575 // parameters or else all other parameters have default arguments.
11576 if (!Ctor->hasOneParamOrDefaultArgs())
11577 return false;
11578
11579 QualType ArgType = Ctor->getParamDecl(0)->getType();
11580 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11581 ArgType = RT->getPointeeType().getUnqualifiedType();
11582
11583 return isStdInitializerList(ArgType, nullptr);
11584}
11585
11586/// Determine whether a using statement is in a context where it will be
11587/// apply in all contexts.
11589 switch (CurContext->getDeclKind()) {
11590 case Decl::TranslationUnit:
11591 return true;
11592 case Decl::LinkageSpec:
11593 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11594 default:
11595 return false;
11596 }
11597}
11598
11599namespace {
11600
11601// Callback to only accept typo corrections that are namespaces.
11602class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11603public:
11604 bool ValidateCandidate(const TypoCorrection &candidate) override {
11605 if (NamedDecl *ND = candidate.getCorrectionDecl())
11607 return false;
11608 }
11609
11610 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11611 return std::make_unique<NamespaceValidatorCCC>(*this);
11612 }
11613};
11614
11615}
11616
11618 CXXScopeSpec &SS,
11619 SourceLocation IdentLoc,
11620 IdentifierInfo *Ident) {
11621 R.clear();
11622 NamespaceValidatorCCC CCC{};
11623 if (TypoCorrection Corrected =
11624 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11626 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11627 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11628 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11629 Ident->getName().equals(CorrectedStr);
11630 S.diagnoseTypo(Corrected,
11631 S.PDiag(diag::err_using_directive_member_suggest)
11632 << Ident << DC << DroppedSpecifier << SS.getRange(),
11633 S.PDiag(diag::note_namespace_defined_here));
11634 } else {
11635 S.diagnoseTypo(Corrected,
11636 S.PDiag(diag::err_using_directive_suggest) << Ident,
11637 S.PDiag(diag::note_namespace_defined_here));
11638 }
11639 R.addDecl(Corrected.getFoundDecl());
11640 return true;
11641 }
11642 return false;
11643}
11644
11646 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11647 SourceLocation IdentLoc,
11648 IdentifierInfo *NamespcName,
11649 const ParsedAttributesView &AttrList) {
11650 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11651 assert(NamespcName && "Invalid NamespcName.");
11652 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11653
11654 // This can only happen along a recovery path.
11655 while (S->isTemplateParamScope())
11656 S = S->getParent();
11657 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11658
11659 UsingDirectiveDecl *UDir = nullptr;
11660 NestedNameSpecifier *Qualifier = nullptr;
11661 if (SS.isSet())
11662 Qualifier = SS.getScopeRep();
11663
11664 // Lookup namespace name.
11665 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11666 LookupParsedName(R, S, &SS);
11667 if (R.isAmbiguous())
11668 return nullptr;
11669
11670 if (R.empty()) {
11671 R.clear();
11672 // Allow "using namespace std;" or "using namespace ::std;" even if
11673 // "std" hasn't been defined yet, for GCC compatibility.
11674 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11675 NamespcName->isStr("std")) {
11676 Diag(IdentLoc, diag::ext_using_undefined_std);
11677 R.addDecl(getOrCreateStdNamespace());
11678 R.resolveKind();
11679 }
11680 // Otherwise, attempt typo correction.
11681 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11682 }
11683
11684 if (!R.empty()) {
11685 NamedDecl *Named = R.getRepresentativeDecl();
11687 assert(NS && "expected namespace decl");
11688
11689 // The use of a nested name specifier may trigger deprecation warnings.
11690 DiagnoseUseOfDecl(Named, IdentLoc);
11691
11692 // C++ [namespace.udir]p1:
11693 // A using-directive specifies that the names in the nominated
11694 // namespace can be used in the scope in which the
11695 // using-directive appears after the using-directive. During
11696 // unqualified name lookup (3.4.1), the names appear as if they
11697 // were declared in the nearest enclosing namespace which
11698 // contains both the using-directive and the nominated
11699 // namespace. [Note: in this context, "contains" means "contains
11700 // directly or indirectly". ]
11701
11702 // Find enclosing context containing both using-directive and
11703 // nominated namespace.
11704 DeclContext *CommonAncestor = NS;
11705 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11706 CommonAncestor = CommonAncestor->getParent();
11707
11708 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11709 SS.getWithLocInContext(Context),
11710 IdentLoc, Named, CommonAncestor);
11711
11712 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11713 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11714 Diag(IdentLoc, diag::warn_using_directive_in_header);
11715 }
11716
11717 PushUsingDirective(S, UDir);
11718 } else {
11719 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11720 }
11721
11722 if (UDir)
11723 ProcessDeclAttributeList(S, UDir, AttrList);
11724
11725 return UDir;
11726}
11727
11729 // If the scope has an associated entity and the using directive is at
11730 // namespace or translation unit scope, add the UsingDirectiveDecl into
11731 // its lookup structure so qualified name lookup can find it.
11732 DeclContext *Ctx = S->getEntity();
11733 if (Ctx && !Ctx->isFunctionOrMethod())
11734 Ctx->addDecl(UDir);
11735 else
11736 // Otherwise, it is at block scope. The using-directives will affect lookup
11737 // only to the end of the scope.
11738 S->PushUsingDirective(UDir);
11739}
11740
11742 SourceLocation UsingLoc,
11743 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11744 UnqualifiedId &Name,
11745 SourceLocation EllipsisLoc,
11746 const ParsedAttributesView &AttrList) {
11747 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11748
11749 if (SS.isEmpty()) {
11750 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11751 return nullptr;
11752 }
11753
11754 switch (Name.getKind()) {
11755 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11756 case UnqualifiedIdKind::IK_Identifier:
11757 case UnqualifiedIdKind::IK_OperatorFunctionId:
11758 case UnqualifiedIdKind::IK_LiteralOperatorId:
11759 case UnqualifiedIdKind::IK_ConversionFunctionId:
11760 break;
11761
11762 case UnqualifiedIdKind::IK_ConstructorName:
11763 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11764 // C++11 inheriting constructors.
11765 Diag(Name.getBeginLoc(),
11766 getLangOpts().CPlusPlus11
11767 ? diag::warn_cxx98_compat_using_decl_constructor
11768 : diag::err_using_decl_constructor)
11769 << SS.getRange();
11770
11771 if (getLangOpts().CPlusPlus11) break;
11772
11773 return nullptr;
11774
11775 case UnqualifiedIdKind::IK_DestructorName:
11776 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11777 return nullptr;
11778
11779 case UnqualifiedIdKind::IK_TemplateId:
11780 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11781 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11782 return nullptr;
11783
11784 case UnqualifiedIdKind::IK_DeductionGuideName:
11785 llvm_unreachable("cannot parse qualified deduction guide name");
11786 }
11787
11788 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11789 DeclarationName TargetName = TargetNameInfo.getName();
11790 if (!TargetName)
11791 return nullptr;
11792
11793 // Warn about access declarations.
11794 if (UsingLoc.isInvalid()) {
11795 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11796 ? diag::err_access_decl
11797 : diag::warn_access_decl_deprecated)
11798 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11799 }
11800
11801 if (EllipsisLoc.isInvalid()) {
11802 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11803 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11804 return nullptr;
11805 } else {
11807 !TargetNameInfo.containsUnexpandedParameterPack()) {
11808 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11809 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11810 EllipsisLoc = SourceLocation();
11811 }
11812 }
11813
11814 NamedDecl *UD =
11815 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11816 SS, TargetNameInfo, EllipsisLoc, AttrList,
11817 /*IsInstantiation*/ false,
11818 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11819 if (UD)
11820 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11821
11822 return UD;
11823}
11824
11826 SourceLocation UsingLoc,
11827 SourceLocation EnumLoc,
11828 const DeclSpec &DS) {
11829 switch (DS.getTypeSpecType()) {
11831 // This will already have been diagnosed
11832 return nullptr;
11833
11834 case DeclSpec::TST_enum:
11835 break;
11836
11838 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11839 return nullptr;
11840
11841 default:
11842 llvm_unreachable("unexpected DeclSpec type");
11843 }
11844
11845 // As with enum-decls, we ignore attributes for now.
11846 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11847 if (auto *Def = Enum->getDefinition())
11848 Enum = Def;
11849
11850 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11852 if (UD)
11853 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11854
11855 return UD;
11856}
11857
11858/// Determine whether a using declaration considers the given
11859/// declarations as "equivalent", e.g., if they are redeclarations of
11860/// the same entity or are both typedefs of the same type.
11861static bool
11863 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11864 return true;
11865
11866 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11867 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11868 return Context.hasSameType(TD1->getUnderlyingType(),
11869 TD2->getUnderlyingType());
11870
11871 // Two using_if_exists using-declarations are equivalent if both are
11872 // unresolved.
11873 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11874 isa<UnresolvedUsingIfExistsDecl>(D2))
11875 return true;
11876
11877 return false;
11878}
11879
11880
11881/// Determines whether to create a using shadow decl for a particular
11882/// decl, given the set of decls existing prior to this using lookup.
11884 const LookupResult &Previous,
11885 UsingShadowDecl *&PrevShadow) {
11886 // Diagnose finding a decl which is not from a base class of the
11887 // current class. We do this now because there are cases where this
11888 // function will silently decide not to build a shadow decl, which
11889 // will pre-empt further diagnostics.
11890 //
11891 // We don't need to do this in C++11 because we do the check once on
11892 // the qualifier.
11893 //
11894 // FIXME: diagnose the following if we care enough:
11895 // struct A { int foo; };
11896 // struct B : A { using A::foo; };
11897 // template <class T> struct C : A {};
11898 // template <class T> struct D : C<T> { using B::foo; } // <---
11899 // This is invalid (during instantiation) in C++03 because B::foo
11900 // resolves to the using decl in B, which is not a base class of D<T>.
11901 // We can't diagnose it immediately because C<T> is an unknown
11902 // specialization. The UsingShadowDecl in D<T> then points directly
11903 // to A::foo, which will look well-formed when we instantiate.
11904 // The right solution is to not collapse the shadow-decl chain.
11905 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11906 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11907 DeclContext *OrigDC = Orig->getDeclContext();
11908
11909 // Handle enums and anonymous structs.
11910 if (isa<EnumDecl>(OrigDC))
11911 OrigDC = OrigDC->getParent();
11912 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11913 while (OrigRec->isAnonymousStructOrUnion())
11914 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11915
11916 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11917 if (OrigDC == CurContext) {
11918 Diag(Using->getLocation(),
11919 diag::err_using_decl_nested_name_specifier_is_current_class)
11920 << Using->getQualifierLoc().getSourceRange();
11921 Diag(Orig->getLocation(), diag::note_using_decl_target);
11922 Using->setInvalidDecl();
11923 return true;
11924 }
11925
11926 Diag(Using->getQualifierLoc().getBeginLoc(),
11927 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11928 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11929 << Using->getQualifierLoc().getSourceRange();
11930 Diag(Orig->getLocation(), diag::note_using_decl_target);
11931 Using->setInvalidDecl();
11932 return true;
11933 }
11934 }
11935
11936 if (Previous.empty()) return false;
11937
11938 NamedDecl *Target = Orig;
11939 if (isa<UsingShadowDecl>(Target))
11940 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11941
11942 // If the target happens to be one of the previous declarations, we
11943 // don't have a conflict.
11944 //
11945 // FIXME: but we might be increasing its access, in which case we
11946 // should redeclare it.
11947 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11948 bool FoundEquivalentDecl = false;
11949 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11950 I != E; ++I) {
11951 NamedDecl *D = (*I)->getUnderlyingDecl();
11952 // We can have UsingDecls in our Previous results because we use the same
11953 // LookupResult for checking whether the UsingDecl itself is a valid
11954 // redeclaration.
11955 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11956 continue;
11957
11958 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11959 // C++ [class.mem]p19:
11960 // If T is the name of a class, then [every named member other than
11961 // a non-static data member] shall have a name different from T
11962 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11963 !isa<IndirectFieldDecl>(Target) &&
11964 !isa<UnresolvedUsingValueDecl>(Target) &&
11965 DiagnoseClassNameShadow(
11966 CurContext,
11968 return true;
11969 }
11970
11971 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11972 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11973 PrevShadow = Shadow;
11974 FoundEquivalentDecl = true;
11975 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11976 // We don't conflict with an existing using shadow decl of an equivalent
11977 // declaration, but we're not a redeclaration of it.
11978 FoundEquivalentDecl = true;
11979 }
11980
11981 if (isVisible(D))
11982 (isa<TagDecl>(D) ? Tag : NonTag) = D;
11983 }
11984
11985 if (FoundEquivalentDecl)
11986 return false;
11987
11988 // Always emit a diagnostic for a mismatch between an unresolved
11989 // using_if_exists and a resolved using declaration in either direction.
11990 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11991 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11992 if (!NonTag && !Tag)
11993 return false;
11994 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11995 Diag(Target->getLocation(), diag::note_using_decl_target);
11996 Diag((NonTag ? NonTag : Tag)->getLocation(),
11997 diag::note_using_decl_conflict);
11998 BUD->setInvalidDecl();
11999 return true;
12000 }
12001
12002 if (FunctionDecl *FD = Target->getAsFunction()) {
12003 NamedDecl *OldDecl = nullptr;
12004 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12005 /*IsForUsingDecl*/ true)) {
12006 case Ovl_Overload:
12007 return false;
12008
12009 case Ovl_NonFunction:
12010 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12011 break;
12012
12013 // We found a decl with the exact signature.
12014 case Ovl_Match:
12015 // If we're in a record, we want to hide the target, so we
12016 // return true (without a diagnostic) to tell the caller not to
12017 // build a shadow decl.
12018 if (CurContext->isRecord())
12019 return true;
12020
12021 // If we're not in a record, this is an error.
12022 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12023 break;
12024 }
12025
12026 Diag(Target->getLocation(), diag::note_using_decl_target);
12027 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12028 BUD->setInvalidDecl();
12029 return true;
12030 }
12031
12032 // Target is not a function.
12033
12034 if (isa<TagDecl>(Target)) {
12035 // No conflict between a tag and a non-tag.
12036 if (!Tag) return false;
12037
12038 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12039 Diag(Target->getLocation(), diag::note_using_decl_target);
12040 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12041 BUD->setInvalidDecl();
12042 return true;
12043 }
12044
12045 // No conflict between a tag and a non-tag.
12046 if (!NonTag) return false;
12047
12048 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12049 Diag(Target->getLocation(), diag::note_using_decl_target);
12050 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12051 BUD->setInvalidDecl();
12052 return true;
12053}
12054
12055/// Determine whether a direct base class is a virtual base class.
12057 if (!Derived->getNumVBases())
12058 return false;
12059 for (auto &B : Derived->bases())
12060 if (B.getType()->getAsCXXRecordDecl() == Base)
12061 return B.isVirtual();
12062 llvm_unreachable("not a direct base class");
12063}
12064
12065/// Builds a shadow declaration corresponding to a 'using' declaration.
12067 NamedDecl *Orig,
12068 UsingShadowDecl *PrevDecl) {
12069 // If we resolved to another shadow declaration, just coalesce them.
12070 NamedDecl *Target = Orig;
12071 if (isa<UsingShadowDecl>(Target)) {
12072 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12073 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12074 }
12075
12076 NamedDecl *NonTemplateTarget = Target;
12077 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12078 NonTemplateTarget = TargetTD->getTemplatedDecl();
12079
12080 UsingShadowDecl *Shadow;
12081 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12082 UsingDecl *Using = cast<UsingDecl>(BUD);
12083 bool IsVirtualBase =
12084 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12085 Using->getQualifier()->getAsRecordDecl());
12087 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12088 } else {
12089 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12090 Target->getDeclName(), BUD, Target);
12091 }
12092 BUD->addShadowDecl(Shadow);
12093
12094 Shadow->setAccess(BUD->getAccess());
12095 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12096 Shadow->setInvalidDecl();
12097
12098 Shadow->setPreviousDecl(PrevDecl);
12099
12100 if (S)
12101 PushOnScopeChains(Shadow, S);
12102 else
12103 CurContext->addDecl(Shadow);
12104
12105
12106 return Shadow;
12107}
12108
12109/// Hides a using shadow declaration. This is required by the current
12110/// using-decl implementation when a resolvable using declaration in a
12111/// class is followed by a declaration which would hide or override
12112/// one or more of the using decl's targets; for example:
12113///
12114/// struct Base { void foo(int); };
12115/// struct Derived : Base {
12116/// using Base::foo;
12117/// void foo(int);
12118/// };
12119///
12120/// The governing language is C++03 [namespace.udecl]p12:
12121///
12122/// When a using-declaration brings names from a base class into a
12123/// derived class scope, member functions in the derived class
12124/// override and/or hide member functions with the same name and
12125/// parameter types in a base class (rather than conflicting).
12126///
12127/// There are two ways to implement this:
12128/// (1) optimistically create shadow decls when they're not hidden
12129/// by existing declarations, or
12130/// (2) don't create any shadow decls (or at least don't make them
12131/// visible) until we've fully parsed/instantiated the class.
12132/// The problem with (1) is that we might have to retroactively remove
12133/// a shadow decl, which requires several O(n) operations because the
12134/// decl structures are (very reasonably) not designed for removal.
12135/// (2) avoids this but is very fiddly and phase-dependent.
12137 if (Shadow->getDeclName().getNameKind() ==
12139 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12140
12141 // Remove it from the DeclContext...
12142 Shadow->getDeclContext()->removeDecl(Shadow);
12143
12144 // ...and the scope, if applicable...
12145 if (S) {
12146 S->RemoveDecl(Shadow);
12147 IdResolver.RemoveDecl(Shadow);
12148 }
12149
12150 // ...and the using decl.
12151 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12152
12153 // TODO: complain somehow if Shadow was used. It shouldn't
12154 // be possible for this to happen, because...?
12155}
12156
12157/// Find the base specifier for a base class with the given type.
12159 QualType DesiredBase,
12160 bool &AnyDependentBases) {
12161 // Check whether the named type is a direct base class.
12162 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12164 for (auto &Base : Derived->bases()) {
12165 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12166 if (CanonicalDesiredBase == BaseType)
12167 return &Base;
12168 if (BaseType->isDependentType())
12169 AnyDependentBases = true;
12170 }
12171 return nullptr;
12172}
12173
12174namespace {
12175class UsingValidatorCCC final : public CorrectionCandidateCallback {
12176public:
12177 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12178 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12179 : HasTypenameKeyword(HasTypenameKeyword),
12180 IsInstantiation(IsInstantiation), OldNNS(NNS),
12181 RequireMemberOf(RequireMemberOf) {}
12182
12183 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12184 NamedDecl *ND = Candidate.getCorrectionDecl();
12185
12186 // Keywords are not valid here.
12187 if (!ND || isa<NamespaceDecl>(ND))
12188 return false;
12189
12190 // Completely unqualified names are invalid for a 'using' declaration.
12191 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12192 return false;
12193
12194 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12195 // reject.
12196
12197 if (RequireMemberOf) {
12198 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12199 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12200 // No-one ever wants a using-declaration to name an injected-class-name
12201 // of a base class, unless they're declaring an inheriting constructor.
12202 ASTContext &Ctx = ND->getASTContext();
12203 if (!Ctx.getLangOpts().CPlusPlus11)
12204 return false;
12205 QualType FoundType = Ctx.getRecordType(FoundRecord);
12206
12207 // Check that the injected-class-name is named as a member of its own
12208 // type; we don't want to suggest 'using Derived::Base;', since that
12209 // means something else.
12210 NestedNameSpecifier *Specifier =
12211 Candidate.WillReplaceSpecifier()
12212 ? Candidate.getCorrectionSpecifier()
12213 : OldNNS;
12214 if (!Specifier->getAsType() ||
12215 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12216 return false;
12217
12218 // Check that this inheriting constructor declaration actually names a
12219 // direct base class of the current class.
12220 bool AnyDependentBases = false;
12221 if (!findDirectBaseWithType(RequireMemberOf,
12222 Ctx.getRecordType(FoundRecord),
12223 AnyDependentBases) &&
12224 !AnyDependentBases)
12225 return false;
12226 } else {
12227 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12228 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12229 return false;
12230
12231 // FIXME: Check that the base class member is accessible?
12232 }
12233 } else {
12234 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12235 if (FoundRecord && FoundRecord->isInjectedClassName())
12236 return false;
12237 }
12238
12239 if (isa<TypeDecl>(ND))
12240 return HasTypenameKeyword || !IsInstantiation;
12241
12242 return !HasTypenameKeyword;
12243 }
12244
12245 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12246 return std::make_unique<UsingValidatorCCC>(*this);
12247 }
12248
12249private:
12250 bool HasTypenameKeyword;
12251 bool IsInstantiation;
12252 NestedNameSpecifier *OldNNS;
12253 CXXRecordDecl *RequireMemberOf;
12254};
12255} // end anonymous namespace
12256
12257/// Remove decls we can't actually see from a lookup being used to declare
12258/// shadow using decls.
12259///
12260/// \param S - The scope of the potential shadow decl
12261/// \param Previous - The lookup of a potential shadow decl's name.
12263 // It is really dumb that we have to do this.
12264 LookupResult::Filter F = Previous.makeFilter();
12265 while (F.hasNext()) {
12266 NamedDecl *D = F.next();
12267 if (!isDeclInScope(D, CurContext, S))
12268 F.erase();
12269 // If we found a local extern declaration that's not ordinarily visible,
12270 // and this declaration is being added to a non-block scope, ignore it.
12271 // We're only checking for scope conflicts here, not also for violations
12272 // of the linkage rules.
12273 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12275 F.erase();
12276 }
12277 F.done();
12278}
12279
12280/// Builds a using declaration.
12281///
12282/// \param IsInstantiation - Whether this call arises from an
12283/// instantiation of an unresolved using declaration. We treat
12284/// the lookup differently for these declarations.
12286 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12287 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12288 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12289 const ParsedAttributesView &AttrList, bool IsInstantiation,
12290 bool IsUsingIfExists) {
12291 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12292 SourceLocation IdentLoc = NameInfo.getLoc();
12293 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12294
12295 // FIXME: We ignore attributes for now.
12296
12297 // For an inheriting constructor declaration, the name of the using
12298 // declaration is the name of a constructor in this class, not in the
12299 // base class.
12300 DeclarationNameInfo UsingName = NameInfo;
12302 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12304 Context.getCanonicalType(Context.getRecordType(RD))));
12305
12306 // Do the redeclaration lookup in the current scope.
12307 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12308 ForVisibleRedeclaration);
12309 Previous.setHideTags(false);
12310 if (S) {
12311 LookupName(Previous, S);
12312
12313 FilterUsingLookup(S, Previous);
12314 } else {
12315 assert(IsInstantiation && "no scope in non-instantiation");
12316 if (CurContext->isRecord())
12317 LookupQualifiedName(Previous, CurContext);
12318 else {
12319 // No redeclaration check is needed here; in non-member contexts we
12320 // diagnosed all possible conflicts with other using-declarations when
12321 // building the template:
12322 //
12323 // For a dependent non-type using declaration, the only valid case is
12324 // if we instantiate to a single enumerator. We check for conflicts
12325 // between shadow declarations we introduce, and we check in the template
12326 // definition for conflicts between a non-type using declaration and any
12327 // other declaration, which together covers all cases.
12328 //
12329 // A dependent typename using declaration will never successfully
12330 // instantiate, since it will always name a class member, so we reject
12331 // that in the template definition.
12332 }
12333 }
12334
12335 // Check for invalid redeclarations.
12336 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12337 SS, IdentLoc, Previous))
12338 return nullptr;
12339
12340 // 'using_if_exists' doesn't make sense on an inherited constructor.
12341 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12343 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12344 return nullptr;
12345 }
12346
12347 DeclContext *LookupContext = computeDeclContext(SS);
12348 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12349 if (!LookupContext || EllipsisLoc.isValid()) {
12350 NamedDecl *D;
12351 // Dependent scope, or an unexpanded pack
12352 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12353 SS, NameInfo, IdentLoc))
12354 return nullptr;
12355
12356 if (HasTypenameKeyword) {
12357 // FIXME: not all declaration name kinds are legal here
12358 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12359 UsingLoc, TypenameLoc,
12360 QualifierLoc,
12361 IdentLoc, NameInfo.getName(),
12362 EllipsisLoc);
12363 } else {
12364 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12365 QualifierLoc, NameInfo, EllipsisLoc);
12366 }
12367 D->setAccess(AS);
12368 CurContext->addDecl(D);
12369 ProcessDeclAttributeList(S, D, AttrList);
12370 return D;
12371 }
12372
12373 auto Build = [&](bool Invalid) {
12374 UsingDecl *UD =
12375 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12376 UsingName, HasTypenameKeyword);
12377 UD->setAccess(AS);
12378 CurContext->addDecl(UD);
12379 ProcessDeclAttributeList(S, UD, AttrList);
12381 return UD;
12382 };
12383 auto BuildInvalid = [&]{ return Build(true); };
12384 auto BuildValid = [&]{ return Build(false); };
12385
12386 if (RequireCompleteDeclContext(SS, LookupContext))
12387 return BuildInvalid();
12388
12389 // Look up the target name.
12390 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12391
12392 // Unlike most lookups, we don't always want to hide tag
12393 // declarations: tag names are visible through the using declaration
12394 // even if hidden by ordinary names, *except* in a dependent context
12395 // where they may be used by two-phase lookup.
12396 if (!IsInstantiation)
12397 R.setHideTags(false);
12398
12399 // For the purposes of this lookup, we have a base object type
12400 // equal to that of the current context.
12401 if (CurContext->isRecord()) {
12403 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12404 }
12405
12406 LookupQualifiedName(R, LookupContext);
12407
12408 // Validate the context, now we have a lookup
12409 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12410 IdentLoc, &R))
12411 return nullptr;
12412
12413 if (R.empty() && IsUsingIfExists)
12414 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12415 UsingName.getName()),
12416 AS_public);
12417
12418 // Try to correct typos if possible. If constructor name lookup finds no
12419 // results, that means the named class has no explicit constructors, and we
12420 // suppressed declaring implicit ones (probably because it's dependent or
12421 // invalid).
12422 if (R.empty() &&
12424 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12425 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12426 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12427 auto *II = NameInfo.getName().getAsIdentifierInfo();
12428 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12429 CurContext->isStdNamespace() &&
12430 isa<TranslationUnitDecl>(LookupContext) &&
12431 getSourceManager().isInSystemHeader(UsingLoc))
12432 return nullptr;
12433 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12434 dyn_cast<CXXRecordDecl>(CurContext));
12435 if (TypoCorrection Corrected =
12436 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12437 CTK_ErrorRecovery)) {
12438 // We reject candidates where DroppedSpecifier == true, hence the
12439 // literal '0' below.
12440 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12441 << NameInfo.getName() << LookupContext << 0
12442 << SS.getRange());
12443
12444 // If we picked a correction with no attached Decl we can't do anything
12445 // useful with it, bail out.
12446 NamedDecl *ND = Corrected.getCorrectionDecl();
12447 if (!ND)
12448 return BuildInvalid();
12449
12450 // If we corrected to an inheriting constructor, handle it as one.
12451 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12452 if (RD && RD->isInjectedClassName()) {
12453 // The parent of the injected class name is the class itself.
12454 RD = cast<CXXRecordDecl>(RD->getParent());
12455
12456 // Fix up the information we'll use to build the using declaration.
12457 if (Corrected.WillReplaceSpecifier()) {
12459 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12460 QualifierLoc.getSourceRange());
12461 QualifierLoc = Builder.getWithLocInContext(Context);
12462 }
12463
12464 // In this case, the name we introduce is the name of a derived class
12465 // constructor.
12466 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12468 Context.getCanonicalType(Context.getRecordType(CurClass))));
12469 UsingName.setNamedTypeInfo(nullptr);
12470 for (auto *Ctor : LookupConstructors(RD))
12471 R.addDecl(Ctor);
12472 R.resolveKind();
12473 } else {
12474 // FIXME: Pick up all the declarations if we found an overloaded
12475 // function.
12476 UsingName.setName(ND->getDeclName());
12477 R.addDecl(ND);
12478 }
12479 } else {
12480 Diag(IdentLoc, diag::err_no_member)
12481 << NameInfo.getName() << LookupContext << SS.getRange();
12482 return BuildInvalid();
12483 }
12484 }
12485
12486 if (R.isAmbiguous())
12487 return BuildInvalid();
12488
12489 if (HasTypenameKeyword) {
12490 // If we asked for a typename and got a non-type decl, error out.
12491 if (!R.getAsSingle<TypeDecl>() &&
12493 Diag(IdentLoc, diag::err_using_typename_non_type);
12494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12495 Diag((*I)->getUnderlyingDecl()->getLocation(),
12496 diag::note_using_decl_target);
12497 return BuildInvalid();
12498 }
12499 } else {
12500 // If we asked for a non-typename and we got a type, error out,
12501 // but only if this is an instantiation of an unresolved using
12502 // decl. Otherwise just silently find the type name.
12503 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12504 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12505 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12506 return BuildInvalid();
12507 }
12508 }
12509
12510 // C++14 [namespace.udecl]p6:
12511 // A using-declaration shall not name a namespace.
12512 if (R.getAsSingle<NamespaceDecl>()) {
12513 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12514 << SS.getRange();
12515 return BuildInvalid();
12516 }
12517
12518 UsingDecl *UD = BuildValid();
12519
12520 // Some additional rules apply to inheriting constructors.
12521 if (UsingName.getName().getNameKind() ==
12523 // Suppress access diagnostics; the access check is instead performed at the
12524 // point of use for an inheriting constructor.
12526 if (CheckInheritingConstructorUsingDecl(UD))
12527 return UD;
12528 }
12529
12530 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12531 UsingShadowDecl *PrevDecl = nullptr;
12532 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12533 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12534 }
12535
12536 return UD;
12537}
12538
12540 SourceLocation UsingLoc,
12541 SourceLocation EnumLoc,
12542 SourceLocation NameLoc,
12543 EnumDecl *ED) {
12544 bool Invalid = false;
12545
12546 if (CurContext->getRedeclContext()->isRecord()) {
12547 /// In class scope, check if this is a duplicate, for better a diagnostic.
12548 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12549 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12550 ForVisibleRedeclaration);
12551
12552 LookupName(Previous, S);
12553
12554 for (NamedDecl *D : Previous)
12555 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12556 if (UED->getEnumDecl() == ED) {
12557 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12558 << SourceRange(EnumLoc, NameLoc);
12559 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12560 Invalid = true;
12561 break;
12562 }
12563 }
12564
12565 if (RequireCompleteEnumDecl(ED, NameLoc))
12566 Invalid = true;
12567
12568 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12569 EnumLoc, NameLoc, ED);
12570 UD->setAccess(AS);
12571 CurContext->addDecl(UD);
12572
12573 if (Invalid) {
12574 UD->setInvalidDecl();
12575 return UD;
12576 }
12577
12578 // Create the shadow decls for each enumerator
12579 for (EnumConstantDecl *EC : ED->enumerators()) {
12580 UsingShadowDecl *PrevDecl = nullptr;
12581 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12582 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12583 ForVisibleRedeclaration);
12584 LookupName(Previous, S);
12585 FilterUsingLookup(S, Previous);
12586
12587 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12588 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12589 }
12590
12591 return UD;
12592}
12593
12595 ArrayRef<NamedDecl *> Expansions) {
12596 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12597 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12598 isa<UsingPackDecl>(InstantiatedFrom));
12599
12600 auto *UPD =
12601 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12602 UPD->setAccess(InstantiatedFrom->getAccess());
12603 CurContext->addDecl(UPD);
12604 return UPD;
12605}
12606
12607/// Additional checks for a using declaration referring to a constructor name.
12609 assert(!UD->hasTypename() && "expecting a constructor name");
12610
12611 const Type *SourceType = UD->getQualifier()->getAsType();
12612 assert(SourceType &&
12613 "Using decl naming constructor doesn't have type in scope spec.");
12614 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12615
12616 // Check whether the named type is a direct base class.
12617 bool AnyDependentBases = false;
12618 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12619 AnyDependentBases);
12620 if (!Base && !AnyDependentBases) {
12621 Diag(UD->getUsingLoc(),
12622 diag::err_using_decl_constructor_not_in_direct_base)
12623 << UD->getNameInfo().getSourceRange()
12624 << QualType(SourceType, 0) << TargetClass;
12625 UD->setInvalidDecl();
12626 return true;
12627 }
12628
12629 if (Base)
12630 Base->setInheritConstructors();
12631
12632 return false;
12633}
12634
12635/// Checks that the given using declaration is not an invalid
12636/// redeclaration. Note that this is checking only for the using decl
12637/// itself, not for any ill-formedness among the UsingShadowDecls.
12639 bool HasTypenameKeyword,
12640 const CXXScopeSpec &SS,
12641 SourceLocation NameLoc,
12642 const LookupResult &Prev) {
12643 NestedNameSpecifier *Qual = SS.getScopeRep();
12644
12645 // C++03 [namespace.udecl]p8:
12646 // C++0x [namespace.udecl]p10:
12647 // A using-declaration is a declaration and can therefore be used
12648 // repeatedly where (and only where) multiple declarations are
12649 // allowed.
12650 //
12651 // That's in non-member contexts.
12652 if (!CurContext->getRedeclContext()->isRecord()) {
12653 // A dependent qualifier outside a class can only ever resolve to an
12654 // enumeration type. Therefore it conflicts with any other non-type
12655 // declaration in the same scope.
12656 // FIXME: How should we check for dependent type-type conflicts at block
12657 // scope?
12658 if (Qual->isDependent() && !HasTypenameKeyword) {
12659 for (auto *D : Prev) {
12660 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12661 bool OldCouldBeEnumerator =
12663 Diag(NameLoc,
12664 OldCouldBeEnumerator ? diag::err_redefinition
12665 : diag::err_redefinition_different_kind)
12666 << Prev.getLookupName();
12667 Diag(D->getLocation(), diag::note_previous_definition);
12668 return true;
12669 }
12670 }
12671 }
12672 return false;
12673 }
12674
12675 const NestedNameSpecifier *CNNS =
12676 Context.getCanonicalNestedNameSpecifier(Qual);
12677 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12678 NamedDecl *D = *I;
12679
12680 bool DTypename;
12681 NestedNameSpecifier *DQual;
12682 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12683 DTypename = UD->hasTypename();
12684 DQual = UD->getQualifier();
12685 } else if (UnresolvedUsingValueDecl *UD
12686 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12687 DTypename = false;
12688 DQual = UD->getQualifier();
12689 } else if (UnresolvedUsingTypenameDecl *UD
12690 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12691 DTypename = true;
12692 DQual = UD->getQualifier();
12693 } else continue;
12694
12695 // using decls differ if one says 'typename' and the other doesn't.
12696 // FIXME: non-dependent using decls?
12697 if (HasTypenameKeyword != DTypename) continue;
12698
12699 // using decls differ if they name different scopes (but note that
12700 // template instantiation can cause this check to trigger when it
12701 // didn't before instantiation).
12702 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12703 continue;
12704
12705 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12706 Diag(D->getLocation(), diag::note_using_decl) << 1;
12707 return true;
12708 }
12709
12710 return false;
12711}
12712
12713/// Checks that the given nested-name qualifier used in a using decl
12714/// in the current context is appropriately related to the current
12715/// scope. If an error is found, diagnoses it and returns true.
12716/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12717/// result of that lookup. UD is likewise nullptr, except when we have an
12718/// already-populated UsingDecl whose shadow decls contain the same information
12719/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12720bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12721 const CXXScopeSpec &SS,
12722 const DeclarationNameInfo &NameInfo,
12723 SourceLocation NameLoc,
12724 const LookupResult *R, const UsingDecl *UD) {
12725 DeclContext *NamedContext = computeDeclContext(SS);
12726 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12727 "resolvable context must have exactly one set of decls");
12728
12729 // C++ 20 permits using an enumerator that does not have a class-hierarchy
12730 // relationship.
12731 bool Cxx20Enumerator = false;
12732 if (NamedContext) {
12733 EnumConstantDecl *EC = nullptr;
12734 if (R)
12735 EC = R->getAsSingle<EnumConstantDecl>();
12736 else if (UD && UD->shadow_size() == 1)
12737 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12738 if (EC)
12739 Cxx20Enumerator = getLangOpts().CPlusPlus20;
12740
12741 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12742 // C++14 [namespace.udecl]p7:
12743 // A using-declaration shall not name a scoped enumerator.
12744 // C++20 p1099 permits enumerators.
12745 if (EC && R && ED->isScoped())
12746 Diag(SS.getBeginLoc(),
12747 getLangOpts().CPlusPlus20
12748 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12749 : diag::ext_using_decl_scoped_enumerator)
12750 << SS.getRange();
12751
12752 // We want to consider the scope of the enumerator
12753 NamedContext = ED->getDeclContext();
12754 }
12755 }
12756
12757 if (!CurContext->isRecord()) {
12758 // C++03 [namespace.udecl]p3:
12759 // C++0x [namespace.udecl]p8:
12760 // A using-declaration for a class member shall be a member-declaration.
12761 // C++20 [namespace.udecl]p7
12762 // ... other than an enumerator ...
12763
12764 // If we weren't able to compute a valid scope, it might validly be a
12765 // dependent class or enumeration scope. If we have a 'typename' keyword,
12766 // the scope must resolve to a class type.
12767 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12768 : !HasTypename)
12769 return false; // OK
12770
12771 Diag(NameLoc,
12772 Cxx20Enumerator
12773 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12774 : diag::err_using_decl_can_not_refer_to_class_member)
12775 << SS.getRange();
12776
12777 if (Cxx20Enumerator)
12778 return false; // OK
12779
12780 auto *RD = NamedContext
12781 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12782 : nullptr;
12783 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12784 // See if there's a helpful fixit
12785
12786 if (!R) {
12787 // We will have already diagnosed the problem on the template
12788 // definition, Maybe we should do so again?
12789 } else if (R->getAsSingle<TypeDecl>()) {
12790 if (getLangOpts().CPlusPlus11) {
12791 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12792 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12793 << 0 // alias declaration
12795 NameInfo.getName().getAsString() +
12796 " = ");
12797 } else {
12798 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12799 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12800 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12801 << 1 // typedef declaration
12802 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12804 InsertLoc, " " + NameInfo.getName().getAsString());
12805 }
12806 } else if (R->getAsSingle<VarDecl>()) {
12807 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12808 // repeating the type of the static data member here.
12809 FixItHint FixIt;
12810 if (getLangOpts().CPlusPlus11) {
12811 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12813 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12814 }
12815
12816 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12817 << 2 // reference declaration
12818 << FixIt;
12819 } else if (R->getAsSingle<EnumConstantDecl>()) {
12820 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12821 // repeating the type of the enumeration here, and we can't do so if
12822 // the type is anonymous.
12823 FixItHint FixIt;
12824 if (getLangOpts().CPlusPlus11) {
12825 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12827 UsingLoc,
12828 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12829 }
12830
12831 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12832 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12833 << FixIt;
12834 }
12835 }
12836
12837 return true; // Fail
12838 }
12839
12840 // If the named context is dependent, we can't decide much.
12841 if (!NamedContext) {
12842 // FIXME: in C++0x, we can diagnose if we can prove that the
12843 // nested-name-specifier does not refer to a base class, which is
12844 // still possible in some cases.
12845
12846 // Otherwise we have to conservatively report that things might be
12847 // okay.
12848 return false;
12849 }
12850
12851 // The current scope is a record.
12852 if (!NamedContext->isRecord()) {
12853 // Ideally this would point at the last name in the specifier,
12854 // but we don't have that level of source info.
12855 Diag(SS.getBeginLoc(),
12856 Cxx20Enumerator
12857 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12858 : diag::err_using_decl_nested_name_specifier_is_not_class)
12859 << SS.getScopeRep() << SS.getRange();
12860
12861 if (Cxx20Enumerator)
12862 return false; // OK
12863
12864 return true;
12865 }
12866
12867 if (!NamedContext->isDependentContext() &&
12868 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12869 return true;
12870
12871 if (getLangOpts().CPlusPlus11) {
12872 // C++11 [namespace.udecl]p3:
12873 // In a using-declaration used as a member-declaration, the
12874 // nested-name-specifier shall name a base class of the class
12875 // being defined.
12876
12877 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12878 cast<CXXRecordDecl>(NamedContext))) {
12879
12880 if (Cxx20Enumerator) {
12881 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12882 << SS.getRange();
12883 return false;
12884 }
12885
12886 if (CurContext == NamedContext) {
12887 Diag(SS.getBeginLoc(),
12888 diag::err_using_decl_nested_name_specifier_is_current_class)
12889 << SS.getRange();
12890 return !getLangOpts().CPlusPlus20;
12891 }
12892
12893 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12894 Diag(SS.getBeginLoc(),
12895 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12896 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12897 << SS.getRange();
12898 }
12899 return true;
12900 }
12901
12902 return false;
12903 }
12904
12905 // C++03 [namespace.udecl]p4:
12906 // A using-declaration used as a member-declaration shall refer
12907 // to a member of a base class of the class being defined [etc.].
12908
12909 // Salient point: SS doesn't have to name a base class as long as
12910 // lookup only finds members from base classes. Therefore we can
12911 // diagnose here only if we can prove that that can't happen,
12912 // i.e. if the class hierarchies provably don't intersect.
12913
12914 // TODO: it would be nice if "definitely valid" results were cached
12915 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12916 // need to be repeated.
12917
12919 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12920 Bases.insert(Base);
12921 return true;
12922 };
12923
12924 // Collect all bases. Return false if we find a dependent base.
12925 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12926 return false;
12927
12928 // Returns true if the base is dependent or is one of the accumulated base
12929 // classes.
12930 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12931 return !Bases.count(Base);
12932 };
12933
12934 // Return false if the class has a dependent base or if it or one
12935 // of its bases is present in the base set of the current context.
12936 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12937 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12938 return false;
12939
12940 Diag(SS.getRange().getBegin(),
12941 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12942 << SS.getScopeRep()
12943 << cast<CXXRecordDecl>(CurContext)
12944 << SS.getRange();
12945
12946 return true;
12947}
12948
12950 MultiTemplateParamsArg TemplateParamLists,
12951 SourceLocation UsingLoc, UnqualifiedId &Name,
12952 const ParsedAttributesView &AttrList,
12953 TypeResult Type, Decl *DeclFromDeclSpec) {
12954 // Skip up to the relevant declaration scope.
12955 while (S->isTemplateParamScope())
12956 S = S->getParent();
12957 assert((S->getFlags() & Scope::DeclScope) &&
12958 "got alias-declaration outside of declaration scope");
12959
12960 if (Type.isInvalid())
12961 return nullptr;
12962
12963 bool Invalid = false;
12964 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12965 TypeSourceInfo *TInfo = nullptr;
12966 GetTypeFromParser(Type.get(), &TInfo);
12967
12968 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12969 return nullptr;
12970
12971 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12972 UPPC_DeclarationType)) {
12973 Invalid = true;
12974 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12975 TInfo->getTypeLoc().getBeginLoc());
12976 }
12977
12978 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12979 TemplateParamLists.size()
12980 ? forRedeclarationInCurContext()
12981 : ForVisibleRedeclaration);
12982 LookupName(Previous, S);
12983
12984 // Warn about shadowing the name of a template parameter.
12985 if (Previous.isSingleResult() &&
12986 Previous.getFoundDecl()->isTemplateParameter()) {
12987 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12988 Previous.clear();
12989 }
12990
12991 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12992 "name in alias declaration must be an identifier");
12993 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12994 Name.StartLocation,
12995 Name.Identifier, TInfo);
12996
12997 NewTD->setAccess(AS);
12998
12999 if (Invalid)
13000 NewTD->setInvalidDecl();
13001
13002 ProcessDeclAttributeList(S, NewTD, AttrList);
13003 AddPragmaAttributes(S, NewTD);
13004
13005 CheckTypedefForVariablyModifiedType(S, NewTD);
13006 Invalid |= NewTD->isInvalidDecl();
13007
13008 bool Redeclaration = false;
13009
13010 NamedDecl *NewND;
13011 if (TemplateParamLists.size()) {
13012 TypeAliasTemplateDecl *OldDecl = nullptr;
13013 TemplateParameterList *OldTemplateParams = nullptr;
13014
13015 if (TemplateParamLists.size() != 1) {
13016 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13017 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13018 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13019 }
13020 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13021
13022 // Check that we can declare a template here.
13023 if (CheckTemplateDeclScope(S, TemplateParams))
13024 return nullptr;
13025
13026 // Only consider previous declarations in the same scope.
13027 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13028 /*ExplicitInstantiationOrSpecialization*/false);
13029 if (!Previous.empty()) {
13030 Redeclaration = true;
13031
13032 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13033 if (!OldDecl && !Invalid) {
13034 Diag(UsingLoc, diag::err_redefinition_different_kind)
13035 << Name.Identifier;
13036
13037 NamedDecl *OldD = Previous.getRepresentativeDecl();
13038 if (OldD->getLocation().isValid())
13039 Diag(OldD->getLocation(), diag::note_previous_definition);
13040
13041 Invalid = true;
13042 }
13043
13044 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13045 if (TemplateParameterListsAreEqual(TemplateParams,
13046 OldDecl->getTemplateParameters(),
13047 /*Complain=*/true,
13048 TPL_TemplateMatch))
13049 OldTemplateParams =
13051 else
13052 Invalid = true;
13053
13054 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13055 if (!Invalid &&
13056 !Context.hasSameType(OldTD->getUnderlyingType(),
13057 NewTD->getUnderlyingType())) {
13058 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13059 // but we can't reasonably accept it.
13060 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13061 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13062 if (OldTD->getLocation().isValid())
13063 Diag(OldTD->getLocation(), diag::note_previous_definition);
13064 Invalid = true;
13065 }
13066 }
13067 }
13068
13069 // Merge any previous default template arguments into our parameters,
13070 // and check the parameter list.
13071 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13072 TPC_TypeAliasTemplate))
13073 return nullptr;
13074
13075 TypeAliasTemplateDecl *NewDecl =
13076 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13077 Name.Identifier, TemplateParams,
13078 NewTD);
13079 NewTD->setDescribedAliasTemplate(NewDecl);
13080
13081 NewDecl->setAccess(AS);
13082
13083 if (Invalid)
13084 NewDecl->setInvalidDecl();
13085 else if (OldDecl) {
13086 NewDecl->setPreviousDecl(OldDecl);
13087 CheckRedeclarationInModule(NewDecl, OldDecl);
13088 }
13089
13090 NewND = NewDecl;
13091 } else {
13092 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13093 setTagNameForLinkagePurposes(TD, NewTD);
13094 handleTagNumbering(TD, S);
13095 }
13096 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13097 NewND = NewTD;
13098 }
13099
13100 PushOnScopeChains(NewND, S);
13101 ActOnDocumentableDecl(NewND);
13102 return NewND;
13103}
13104
13106 SourceLocation AliasLoc,
13107 IdentifierInfo *Alias, CXXScopeSpec &SS,
13108 SourceLocation IdentLoc,
13109 IdentifierInfo *Ident) {
13110
13111 // Lookup the namespace name.
13112 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13113 LookupParsedName(R, S, &SS);
13114
13115 if (R.isAmbiguous())
13116 return nullptr;
13117
13118 if (R.empty()) {
13119 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13120 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13121 return nullptr;
13122 }
13123 }
13124 assert(!R.isAmbiguous() && !R.empty());
13126
13127 // Check if we have a previous declaration with the same name.
13128 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13129 ForVisibleRedeclaration);
13130 LookupName(PrevR, S);
13131
13132 // Check we're not shadowing a template parameter.
13133 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13134 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13135 PrevR.clear();
13136 }
13137
13138 // Filter out any other lookup result from an enclosing scope.
13139 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13140 /*AllowInlineNamespace*/false);
13141
13142 // Find the previous declaration and check that we can redeclare it.
13143 NamespaceAliasDecl *Prev = nullptr;
13144 if (PrevR.isSingleResult()) {
13145 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13146 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13147 // We already have an alias with the same name that points to the same
13148 // namespace; check that it matches.
13149 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13150 Prev = AD;
13151 } else if (isVisible(PrevDecl)) {
13152 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13153 << Alias;
13154 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13155 << AD->getNamespace();
13156 return nullptr;
13157 }
13158 } else if (isVisible(PrevDecl)) {
13159 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13160 ? diag::err_redefinition
13161 : diag::err_redefinition_different_kind;
13162 Diag(AliasLoc, DiagID) << Alias;
13163 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13164 return nullptr;
13165 }
13166 }
13167
13168 // The use of a nested name specifier may trigger deprecation warnings.
13169 DiagnoseUseOfDecl(ND, IdentLoc);
13170
13172 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13173 Alias, SS.getWithLocInContext(Context),
13174 IdentLoc, ND);
13175 if (Prev)
13176 AliasDecl->setPreviousDecl(Prev);
13177
13178 PushOnScopeChains(AliasDecl, S);
13179 return AliasDecl;
13180}
13181
13182namespace {
13183struct SpecialMemberExceptionSpecInfo
13184 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13185 SourceLocation Loc;
13187
13188 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13191 SourceLocation Loc)
13192 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13193
13194 bool visitBase(CXXBaseSpecifier *Base);
13195 bool visitField(FieldDecl *FD);
13196
13197 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13198 unsigned Quals);
13199
13200 void visitSubobjectCall(Subobject Subobj,
13202};
13203}
13204
13205bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13206 auto *RT = Base->getType()->getAs<RecordType>();
13207 if (!RT)
13208 return false;
13209
13210 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13211 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13212 if (auto *BaseCtor = SMOR.getMethod()) {
13213 visitSubobjectCall(Base, BaseCtor);
13214 return false;
13215 }
13216
13217 visitClassSubobject(BaseClass, Base, 0);
13218 return false;
13219}
13220
13221bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13223 Expr *E = FD->getInClassInitializer();
13224 if (!E)
13225 // FIXME: It's a little wasteful to build and throw away a
13226 // CXXDefaultInitExpr here.
13227 // FIXME: We should have a single context note pointing at Loc, and
13228 // this location should be MD->getLocation() instead, since that's
13229 // the location where we actually use the default init expression.
13230 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13231 if (E)
13232 ExceptSpec.CalledExpr(E);
13233 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13234 ->getAs<RecordType>()) {
13235 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13236 FD->getType().getCVRQualifiers());
13237 }
13238 return false;
13239}
13240
13241void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13242 Subobject Subobj,
13243 unsigned Quals) {
13244 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13245 bool IsMutable = Field && Field->isMutable();
13246 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13247}
13248
13249void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13250 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13251 // Note, if lookup fails, it doesn't matter what exception specification we
13252 // choose because the special member will be deleted.
13253 if (CXXMethodDecl *MD = SMOR.getMethod())
13254 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13255}
13256
13258 llvm::APSInt Result;
13260 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13261 ExplicitSpec.setExpr(Converted.get());
13262 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13263 ExplicitSpec.setKind(Result.getBoolValue()
13264 ? ExplicitSpecKind::ResolvedTrue
13265 : ExplicitSpecKind::ResolvedFalse);
13266 return true;
13267 }
13268 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13269 return false;
13270}
13271
13273 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13274 if (!ExplicitExpr->isTypeDependent())
13275 tryResolveExplicitSpecifier(ES);
13276 return ES;
13277}
13278
13283 ComputingExceptionSpec CES(S, MD, Loc);
13284
13285 CXXRecordDecl *ClassDecl = MD->getParent();
13286
13287 // C++ [except.spec]p14:
13288 // An implicitly declared special member function (Clause 12) shall have an
13289 // exception-specification. [...]
13290 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13291 if (ClassDecl->isInvalidDecl())
13292 return Info.ExceptSpec;
13293
13294 // FIXME: If this diagnostic fires, we're probably missing a check for
13295 // attempting to resolve an exception specification before it's known
13296 // at a higher level.
13297 if (S.RequireCompleteType(MD->getLocation(),
13298 S.Context.getRecordType(ClassDecl),
13299 diag::err_exception_spec_incomplete_type))
13300 return Info.ExceptSpec;
13301
13302 // C++1z [except.spec]p7:
13303 // [Look for exceptions thrown by] a constructor selected [...] to
13304 // initialize a potentially constructed subobject,
13305 // C++1z [except.spec]p8:
13306 // The exception specification for an implicitly-declared destructor, or a
13307 // destructor without a noexcept-specifier, is potentially-throwing if and
13308 // only if any of the destructors for any of its potentially constructed
13309 // subojects is potentially throwing.
13310 // FIXME: We respect the first rule but ignore the "potentially constructed"
13311 // in the second rule to resolve a core issue (no number yet) that would have
13312 // us reject:
13313 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13314 // struct B : A {};
13315 // struct C : B { void f(); };
13316 // ... due to giving B::~B() a non-throwing exception specification.
13317 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13318 : Info.VisitAllBases);
13319
13320 return Info.ExceptSpec;
13321}
13322
13323namespace {
13324/// RAII object to register a special member as being currently declared.
13325struct DeclaringSpecialMember {
13326 Sema &S;
13328 Sema::ContextRAII SavedContext;
13329 bool WasAlreadyBeingDeclared;
13330
13331 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13332 : S(S), D(RD, CSM), SavedContext(S, RD) {
13333 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13334 if (WasAlreadyBeingDeclared)
13335 // This almost never happens, but if it does, ensure that our cache
13336 // doesn't contain a stale result.
13337 S.SpecialMemberCache.clear();
13338 else {
13339 // Register a note to be produced if we encounter an error while
13340 // declaring the special member.
13341 Sema::CodeSynthesisContext Ctx;
13342 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13343 // FIXME: We don't have a location to use here. Using the class's
13344 // location maintains the fiction that we declare all special members
13345 // with the class, but (1) it's not clear that lying about that helps our
13346 // users understand what's going on, and (2) there may be outer contexts
13347 // on the stack (some of which are relevant) and printing them exposes
13348 // our lies.
13349 Ctx.PointOfInstantiation = RD->getLocation();
13350 Ctx.Entity = RD;
13351 Ctx.SpecialMember = CSM;
13352 S.pushCodeSynthesisContext(Ctx);
13353 }
13354 }
13355 ~DeclaringSpecialMember() {
13356 if (!WasAlreadyBeingDeclared) {
13357 S.SpecialMembersBeingDeclared.erase(D);
13359 }
13360 }
13361
13362 /// Are we already trying to declare this special member?
13363 bool isAlreadyBeingDeclared() const {
13364 return WasAlreadyBeingDeclared;
13365 }
13366};
13367}
13368
13370 // Look up any existing declarations, but don't trigger declaration of all
13371 // implicit special members with this name.
13372 DeclarationName Name = FD->getDeclName();
13373 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13374 ForExternalRedeclaration);
13375 for (auto *D : FD->getParent()->lookup(Name))
13376 if (auto *Acceptable = R.getAcceptableDecl(D))
13377 R.addDecl(Acceptable);
13378 R.resolveKind();
13380
13381 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13383}
13384
13385void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13386 QualType ResultTy,
13387 ArrayRef<QualType> Args) {
13388 // Build an exception specification pointing back at this constructor.
13390
13391 LangAS AS = getDefaultCXXMethodAddrSpace();
13392 if (AS != LangAS::Default) {
13393 EPI.TypeQuals.addAddressSpace(AS);
13394 }
13395
13396 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13397 SpecialMem->setType(QT);
13398
13399 // During template instantiation of implicit special member functions we need
13400 // a reliable TypeSourceInfo for the function prototype in order to allow
13401 // functions to be substituted.
13402 if (inTemplateInstantiation() &&
13403 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13404 TypeSourceInfo *TSI =
13405 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13406 SpecialMem->setTypeSourceInfo(TSI);
13407 }
13408}
13409
13411 CXXRecordDecl *ClassDecl) {
13412 // C++ [class.ctor]p5:
13413 // A default constructor for a class X is a constructor of class X
13414 // that can be called without an argument. If there is no
13415 // user-declared constructor for class X, a default constructor is
13416 // implicitly declared. An implicitly-declared default constructor
13417 // is an inline public member of its class.
13418 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13419 "Should not build implicit default constructor!");
13420
13421 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13422 if (DSM.isAlreadyBeingDeclared())
13423 return nullptr;
13424
13425 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13426 CXXDefaultConstructor,
13427 false);
13428
13429 // Create the actual constructor declaration.
13430 CanQualType ClassType
13431 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13432 SourceLocation ClassLoc = ClassDecl->getLocation();
13433 DeclarationName Name
13434 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13435 DeclarationNameInfo NameInfo(Name, ClassLoc);
13437 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13438 /*TInfo=*/nullptr, ExplicitSpecifier(),
13439 getCurFPFeatures().isFPConstrained(),
13440 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13441 Constexpr ? ConstexprSpecKind::Constexpr
13442 : ConstexprSpecKind::Unspecified);
13443 DefaultCon->setAccess(AS_public);
13444 DefaultCon->setDefaulted();
13445
13446 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13447
13448 if (getLangOpts().CUDA)
13449 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13450 DefaultCon,
13451 /* ConstRHS */ false,
13452 /* Diagnose */ false);
13453
13454 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13455 // constructors is easy to compute.
13456 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13457
13458 // Note that we have declared this constructor.
13459 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13460
13461 Scope *S = getScopeForContext(ClassDecl);
13462 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13463
13464 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13465 SetDeclDeleted(DefaultCon, ClassLoc);
13466
13467 if (S)
13468 PushOnScopeChains(DefaultCon, S, false);
13469 ClassDecl->addDecl(DefaultCon);
13470
13471 return DefaultCon;
13472}
13473
13475 CXXConstructorDecl *Constructor) {
13476 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13477 !Constructor->doesThisDeclarationHaveABody() &&
13478 !Constructor->isDeleted()) &&
13479 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13480 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13481 return;
13482
13483 CXXRecordDecl *ClassDecl = Constructor->getParent();
13484 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13485
13486 SynthesizedFunctionScope Scope(*this, Constructor);
13487
13488 // The exception specification is needed because we are defining the
13489 // function.
13490 ResolveExceptionSpec(CurrentLocation,
13491 Constructor->getType()->castAs<FunctionProtoType>());
13492 MarkVTableUsed(CurrentLocation, ClassDecl);
13493
13494 // Add a context note for diagnostics produced after this point.
13495 Scope.addContextNote(CurrentLocation);
13496
13497 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13498 Constructor->setInvalidDecl();
13499 return;
13500 }
13501
13502 SourceLocation Loc = Constructor->getEndLoc().isValid()
13503 ? Constructor->getEndLoc()
13504 : Constructor->getLocation();
13505 Constructor->setBody(new (Context) CompoundStmt(Loc));
13506 Constructor->markUsed(Context);
13507
13508 if (ASTMutationListener *L = getASTMutationListener()) {
13509 L->CompletedImplicitDefinition(Constructor);
13510 }
13511
13512 DiagnoseUninitializedFields(*this, Constructor);
13513}
13514
13516 // Perform any delayed checks on exception specifications.
13517 CheckDelayedMemberExceptionSpecs();
13518}
13519
13520/// Find or create the fake constructor we synthesize to model constructing an
13521/// object of a derived class via a constructor of a base class.
13524 CXXConstructorDecl *BaseCtor,
13526 CXXRecordDecl *Derived = Shadow->getParent();
13527 SourceLocation UsingLoc = Shadow->getLocation();
13528
13529 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13530 // For now we use the name of the base class constructor as a member of the
13531 // derived class to indicate a (fake) inherited constructor name.
13532 DeclarationName Name = BaseCtor->getDeclName();
13533
13534 // Check to see if we already have a fake constructor for this inherited
13535 // constructor call.
13536 for (NamedDecl *Ctor : Derived->lookup(Name))
13537 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13538 ->getInheritedConstructor()
13539 .getConstructor(),
13540 BaseCtor))
13541 return cast<CXXConstructorDecl>(Ctor);
13542
13543 DeclarationNameInfo NameInfo(Name, UsingLoc);
13544 TypeSourceInfo *TInfo =
13545 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13546 FunctionProtoTypeLoc ProtoLoc =
13548
13549 // Check the inherited constructor is valid and find the list of base classes
13550 // from which it was inherited.
13551 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13552
13553 bool Constexpr =
13554 BaseCtor->isConstexpr() &&
13555 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13556 false, BaseCtor, &ICI);
13557
13559 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13560 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13561 /*isInline=*/true,
13562 /*isImplicitlyDeclared=*/true,
13563 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13564 InheritedConstructor(Shadow, BaseCtor),
13565 BaseCtor->getTrailingRequiresClause());
13566 if (Shadow->isInvalidDecl())
13567 DerivedCtor->setInvalidDecl();
13568
13569 // Build an unevaluated exception specification for this fake constructor.
13570 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13573 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13574 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13575 FPT->getParamTypes(), EPI));
13576
13577 // Build the parameter declarations.
13579 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13580 TypeSourceInfo *TInfo =
13581 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13583 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13584 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13585 PD->setScopeInfo(0, I);
13586 PD->setImplicit();
13587 // Ensure attributes are propagated onto parameters (this matters for
13588 // format, pass_object_size, ...).
13589 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13590 ParamDecls.push_back(PD);
13591 ProtoLoc.setParam(I, PD);
13592 }
13593
13594 // Set up the new constructor.
13595 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13596 DerivedCtor->setAccess(BaseCtor->getAccess());
13597 DerivedCtor->setParams(ParamDecls);
13598 Derived->addDecl(DerivedCtor);
13599
13600 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13601 SetDeclDeleted(DerivedCtor, UsingLoc);
13602
13603 return DerivedCtor;
13604}
13605
13607 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13609 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13610 /*Diagnose*/true);
13611}
13612
13614 CXXConstructorDecl *Constructor) {
13615 CXXRecordDecl *ClassDecl = Constructor->getParent();
13616 assert(Constructor->getInheritedConstructor() &&
13617 !Constructor->doesThisDeclarationHaveABody() &&
13618 !Constructor->isDeleted());
13619 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13620 return;
13621
13622 // Initializations are performed "as if by a defaulted default constructor",
13623 // so enter the appropriate scope.
13624 SynthesizedFunctionScope Scope(*this, Constructor);
13625
13626 // The exception specification is needed because we are defining the
13627 // function.
13628 ResolveExceptionSpec(CurrentLocation,
13629 Constructor->getType()->castAs<FunctionProtoType>());
13630 MarkVTableUsed(CurrentLocation, ClassDecl);
13631
13632 // Add a context note for diagnostics produced after this point.
13633 Scope.addContextNote(CurrentLocation);
13634
13636 Constructor->getInheritedConstructor().getShadowDecl();
13637 CXXConstructorDecl *InheritedCtor =
13638 Constructor->getInheritedConstructor().getConstructor();
13639
13640 // [class.inhctor.init]p1:
13641 // initialization proceeds as if a defaulted default constructor is used to
13642 // initialize the D object and each base class subobject from which the
13643 // constructor was inherited
13644
13645 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13646 CXXRecordDecl *RD = Shadow->getParent();
13647 SourceLocation InitLoc = Shadow->getLocation();
13648
13649 // Build explicit initializers for all base classes from which the
13650 // constructor was inherited.
13652 for (bool VBase : {false, true}) {
13653 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13654 if (B.isVirtual() != VBase)
13655 continue;
13656
13657 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13658 if (!BaseRD)
13659 continue;
13660
13661 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13662 if (!BaseCtor.first)
13663 continue;
13664
13665 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13666 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13667 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13668
13669 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13670 Inits.push_back(new (Context) CXXCtorInitializer(
13671 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13672 SourceLocation()));
13673 }
13674 }
13675
13676 // We now proceed as if for a defaulted default constructor, with the relevant
13677 // initializers replaced.
13678
13679 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13680 Constructor->setInvalidDecl();
13681 return;
13682 }
13683
13684 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13685 Constructor->markUsed(Context);
13686
13687 if (ASTMutationListener *L = getASTMutationListener()) {
13688 L->CompletedImplicitDefinition(Constructor);
13689 }
13690
13691 DiagnoseUninitializedFields(*this, Constructor);
13692}
13693
13695 // C++ [class.dtor]p2:
13696 // If a class has no user-declared destructor, a destructor is
13697 // declared implicitly. An implicitly-declared destructor is an
13698 // inline public member of its class.
13699 assert(ClassDecl->needsImplicitDestructor());
13700
13701 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13702 if (DSM.isAlreadyBeingDeclared())
13703 return nullptr;
13704
13705 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13706 CXXDestructor,
13707 false);
13708
13709 // Create the actual destructor declaration.
13710 CanQualType ClassType
13711 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13712 SourceLocation ClassLoc = ClassDecl->getLocation();
13713 DeclarationName Name
13714 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13715 DeclarationNameInfo NameInfo(Name, ClassLoc);
13717 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13718 getCurFPFeatures().isFPConstrained(),
13719 /*isInline=*/true,
13720 /*isImplicitlyDeclared=*/true,
13721 Constexpr ? ConstexprSpecKind::Constexpr
13722 : ConstexprSpecKind::Unspecified);
13723 Destructor->setAccess(AS_public);
13724 Destructor->setDefaulted();
13725
13726 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13727
13728 if (getLangOpts().CUDA)
13729 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13730 Destructor,
13731 /* ConstRHS */ false,
13732 /* Diagnose */ false);
13733
13734 // We don't need to use SpecialMemberIsTrivial here; triviality for
13735 // destructors is easy to compute.
13736 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13737 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13738 ClassDecl->hasTrivialDestructorForCall());
13739
13740 // Note that we have declared this destructor.
13741 ++getASTContext().NumImplicitDestructorsDeclared;
13742
13743 Scope *S = getScopeForContext(ClassDecl);
13744 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13745
13746 // We can't check whether an implicit destructor is deleted before we complete
13747 // the definition of the class, because its validity depends on the alignment
13748 // of the class. We'll check this from ActOnFields once the class is complete.
13749 if (ClassDecl->isCompleteDefinition() &&
13750 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13751 SetDeclDeleted(Destructor, ClassLoc);
13752
13753 // Introduce this destructor into its scope.
13754 if (S)
13755 PushOnScopeChains(Destructor, S, false);
13756 ClassDecl->addDecl(Destructor);
13757
13758 return Destructor;
13759}
13760
13762 CXXDestructorDecl *Destructor) {
13763 assert((Destructor->isDefaulted() &&
13764 !Destructor->doesThisDeclarationHaveABody() &&
13765 !Destructor->isDeleted()) &&
13766 "DefineImplicitDestructor - call it for implicit default dtor");
13767 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13768 return;
13769
13770 CXXRecordDecl *ClassDecl = Destructor->getParent();
13771 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13772
13773 SynthesizedFunctionScope Scope(*this, Destructor);
13774
13775 // The exception specification is needed because we are defining the
13776 // function.
13777 ResolveExceptionSpec(CurrentLocation,
13778 Destructor->getType()->castAs<FunctionProtoType>());
13779 MarkVTableUsed(CurrentLocation, ClassDecl);
13780
13781 // Add a context note for diagnostics produced after this point.
13782 Scope.addContextNote(CurrentLocation);
13783
13784 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13785 Destructor->getParent());
13786
13787 if (CheckDestructor(Destructor)) {
13788 Destructor->setInvalidDecl();
13789 return;
13790 }
13791
13792 SourceLocation Loc = Destructor->getEndLoc().isValid()
13793 ? Destructor->getEndLoc()
13794 : Destructor->getLocation();
13795 Destructor->setBody(new (Context) CompoundStmt(Loc));
13796 Destructor->markUsed(Context);
13797
13798 if (ASTMutationListener *L = getASTMutationListener()) {
13799 L->CompletedImplicitDefinition(Destructor);
13800 }
13801}
13802
13804 CXXDestructorDecl *Destructor) {
13805 if (Destructor->isInvalidDecl())
13806 return;
13807
13808 CXXRecordDecl *ClassDecl = Destructor->getParent();
13809 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13810 "implicit complete dtors unneeded outside MS ABI");
13811 assert(ClassDecl->getNumVBases() > 0 &&
13812 "complete dtor only exists for classes with vbases");
13813
13814 SynthesizedFunctionScope Scope(*this, Destructor);
13815
13816 // Add a context note for diagnostics produced after this point.
13817 Scope.addContextNote(CurrentLocation);
13818
13819 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13820}
13821
13822/// Perform any semantic analysis which needs to be delayed until all
13823/// pending class member declarations have been parsed.
13825 // If the context is an invalid C++ class, just suppress these checks.
13826 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13827 if (Record->isInvalidDecl()) {
13828 DelayedOverridingExceptionSpecChecks.clear();
13829 DelayedEquivalentExceptionSpecChecks.clear();
13830 return;
13831 }
13833 }
13834}
13835
13837 referenceDLLExportedClassMethods();
13838
13839 if (!DelayedDllExportMemberFunctions.empty()) {
13841 std::swap(DelayedDllExportMemberFunctions, WorkList);
13842 for (CXXMethodDecl *M : WorkList) {
13843 DefineDefaultedFunction(*this, M, M->getLocation());
13844
13845 // Pass the method to the consumer to get emitted. This is not necessary
13846 // for explicit instantiation definitions, as they will get emitted
13847 // anyway.
13848 if (M->getParent()->getTemplateSpecializationKind() !=
13850 ActOnFinishInlineFunctionDef(M);
13851 }
13852 }
13853}
13854
13856 if (!DelayedDllExportClasses.empty()) {
13857 // Calling ReferenceDllExportedMembers might cause the current function to
13858 // be called again, so use a local copy of DelayedDllExportClasses.
13860 std::swap(DelayedDllExportClasses, WorkList);
13861 for (CXXRecordDecl *Class : WorkList)
13862 ReferenceDllExportedMembers(*this, Class);
13863 }
13864}
13865
13867 assert(getLangOpts().CPlusPlus11 &&
13868 "adjusting dtor exception specs was introduced in c++11");
13869
13870 if (Destructor->isDependentContext())
13871 return;
13872
13873 // C++11 [class.dtor]p3:
13874 // A declaration of a destructor that does not have an exception-
13875 // specification is implicitly considered to have the same exception-
13876 // specification as an implicit declaration.
13877 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13878 if (DtorType->hasExceptionSpec())
13879 return;
13880
13881 // Replace the destructor's type, building off the existing one. Fortunately,
13882 // the only thing of interest in the destructor type is its extended info.
13883 // The return and arguments are fixed.
13884 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13886 EPI.ExceptionSpec.SourceDecl = Destructor;
13887 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13888
13889 // FIXME: If the destructor has a body that could throw, and the newly created
13890 // spec doesn't allow exceptions, we should emit a warning, because this
13891 // change in behavior can break conforming C++03 programs at runtime.
13892 // However, we don't have a body or an exception specification yet, so it
13893 // needs to be done somewhere else.
13894}
13895
13896namespace {
13897/// An abstract base class for all helper classes used in building the
13898// copy/move operators. These classes serve as factory functions and help us
13899// avoid using the same Expr* in the AST twice.
13900class ExprBuilder {
13901 ExprBuilder(const ExprBuilder&) = delete;
13902 ExprBuilder &operator=(const ExprBuilder&) = delete;
13903
13904protected:
13905 static Expr *assertNotNull(Expr *E) {
13906 assert(E && "Expression construction must not fail.");
13907 return E;
13908 }
13909
13910public:
13911 ExprBuilder() {}
13912 virtual ~ExprBuilder() {}
13913
13914 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13915};
13916
13917class RefBuilder: public ExprBuilder {
13918 VarDecl *Var;
13919 QualType VarType;
13920
13921public:
13922 Expr *build(Sema &S, SourceLocation Loc) const override {
13923 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13924 }
13925
13926 RefBuilder(VarDecl *Var, QualType VarType)
13927 : Var(Var), VarType(VarType) {}
13928};
13929
13930class ThisBuilder: public ExprBuilder {
13931public:
13932 Expr *build(Sema &S, SourceLocation Loc) const override {
13933 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13934 }
13935};
13936
13937class CastBuilder: public ExprBuilder {
13938 const ExprBuilder &Builder;
13939 QualType Type;
13940 ExprValueKind Kind;
13941 const CXXCastPath &Path;
13942
13943public:
13944 Expr *build(Sema &S, SourceLocation Loc) const override {
13945 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13946 CK_UncheckedDerivedToBase, Kind,
13947 &Path).get());
13948 }
13949
13950 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13951 const CXXCastPath &Path)
13952 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13953};
13954
13955class DerefBuilder: public ExprBuilder {
13956 const ExprBuilder &Builder;
13957
13958public:
13959 Expr *build(Sema &S, SourceLocation Loc) const override {
13960 return assertNotNull(
13961 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13962 }
13963
13964 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13965};
13966
13967class MemberBuilder: public ExprBuilder {
13968 const ExprBuilder &Builder;
13969 QualType Type;
13970 CXXScopeSpec SS;
13971 bool IsArrow;
13972 LookupResult &MemberLookup;
13973
13974public:
13975 Expr *build(Sema &S, SourceLocation Loc) const override {
13976 return assertNotNull(S.BuildMemberReferenceExpr(
13977 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13978 nullptr, MemberLookup, nullptr, nullptr).get());
13979 }
13980
13981 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13982 LookupResult &MemberLookup)
13983 : Builder(Builder), Type(Type), IsArrow(IsArrow),
13984 MemberLookup(MemberLookup) {}
13985};
13986
13987class MoveCastBuilder: public ExprBuilder {
13988 const ExprBuilder &Builder;
13989
13990public:
13991 Expr *build(Sema &S, SourceLocation Loc) const override {
13992 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13993 }
13994
13995 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13996};
13997
13998class LvalueConvBuilder: public ExprBuilder {
13999 const ExprBuilder &Builder;
14000
14001public:
14002 Expr *build(Sema &S, SourceLocation Loc) const override {
14003 return assertNotNull(
14004 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14005 }
14006
14007 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14008};
14009
14010class SubscriptBuilder: public ExprBuilder {
14011 const ExprBuilder &Base;
14012 const ExprBuilder &Index;
14013
14014public:
14015 Expr *build(Sema &S, SourceLocation Loc) const override {
14016 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14017 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14018 }
14019
14020 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14021 : Base(Base), Index(Index) {}
14022};
14023
14024} // end anonymous namespace
14025
14026/// When generating a defaulted copy or move assignment operator, if a field
14027/// should be copied with __builtin_memcpy rather than via explicit assignments,
14028/// do so. This optimization only applies for arrays of scalars, and for arrays
14029/// of class type where the selected copy/move-assignment operator is trivial.
14030static StmtResult
14032 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14033 // Compute the size of the memory buffer to be copied.
14034 QualType SizeType = S.Context.getSizeType();
14035 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14037
14038 // Take the address of the field references for "from" and "to". We
14039 // directly construct UnaryOperators here because semantic analysis
14040 // does not permit us to take the address of an xvalue.
14041 Expr *From = FromB.build(S, Loc);
14042 From = UnaryOperator::Create(
14043 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14044 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14045 Expr *To = ToB.build(S, Loc);
14047 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14048 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14049
14050 const Type *E = T->getBaseElementTypeUnsafe();
14051 bool NeedsCollectableMemCpy =
14052 E->isRecordType() &&
14053 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14054
14055 // Create a reference to the __builtin_objc_memmove_collectable function
14056 StringRef MemCpyName = NeedsCollectableMemCpy ?
14057 "__builtin_objc_memmove_collectable" :
14058 "__builtin_memcpy";
14059 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14061 S.LookupName(R, S.TUScope, true);
14062
14063 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14064 if (!MemCpy)
14065 // Something went horribly wrong earlier, and we will have complained
14066 // about it.
14067 return StmtError();
14068
14069 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14070 VK_PRValue, Loc, nullptr);
14071 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14072
14073 Expr *CallArgs[] = {
14074 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14075 };
14076 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14077 Loc, CallArgs, Loc);
14078
14079 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14080 return Call.getAs<Stmt>();
14081}
14082
14083/// Builds a statement that copies/moves the given entity from \p From to
14084/// \c To.
14085///
14086/// This routine is used to copy/move the members of a class with an
14087/// implicitly-declared copy/move assignment operator. When the entities being
14088/// copied are arrays, this routine builds for loops to copy them.
14089///
14090/// \param S The Sema object used for type-checking.
14091///
14092/// \param Loc The location where the implicit copy/move is being generated.
14093///
14094/// \param T The type of the expressions being copied/moved. Both expressions
14095/// must have this type.
14096///
14097/// \param To The expression we are copying/moving to.
14098///
14099/// \param From The expression we are copying/moving from.
14100///
14101/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14102/// Otherwise, it's a non-static member subobject.
14103///
14104/// \param Copying Whether we're copying or moving.
14105///
14106/// \param Depth Internal parameter recording the depth of the recursion.
14107///
14108/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14109/// if a memcpy should be used instead.
14110static StmtResult
14112 const ExprBuilder &To, const ExprBuilder &From,
14113 bool CopyingBaseSubobject, bool Copying,
14114 unsigned Depth = 0) {
14115 // C++11 [class.copy]p28:
14116 // Each subobject is assigned in the manner appropriate to its type:
14117 //
14118 // - if the subobject is of class type, as if by a call to operator= with
14119 // the subobject as the object expression and the corresponding
14120 // subobject of x as a single function argument (as if by explicit
14121 // qualification; that is, ignoring any possible virtual overriding
14122 // functions in more derived classes);
14123 //
14124 // C++03 [class.copy]p13:
14125 // - if the subobject is of class type, the copy assignment operator for
14126 // the class is used (as if by explicit qualification; that is,
14127 // ignoring any possible virtual overriding functions in more derived
14128 // classes);
14129 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14130 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14131
14132 // Look for operator=.
14133 DeclarationName Name
14135 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14136 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14137
14138 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14139 // operator.
14140 if (!S.getLangOpts().CPlusPlus11) {
14141 LookupResult::Filter F = OpLookup.makeFilter();
14142 while (F.hasNext()) {
14143 NamedDecl *D = F.next();
14144 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14145 if (Method->isCopyAssignmentOperator() ||
14146 (!Copying && Method->isMoveAssignmentOperator()))
14147 continue;
14148
14149 F.erase();
14150 }
14151 F.done();
14152 }
14153
14154 // Suppress the protected check (C++ [class.protected]) for each of the
14155 // assignment operators we found. This strange dance is required when
14156 // we're assigning via a base classes's copy-assignment operator. To
14157 // ensure that we're getting the right base class subobject (without
14158 // ambiguities), we need to cast "this" to that subobject type; to
14159 // ensure that we don't go through the virtual call mechanism, we need
14160 // to qualify the operator= name with the base class (see below). However,
14161 // this means that if the base class has a protected copy assignment
14162 // operator, the protected member access check will fail. So, we
14163 // rewrite "protected" access to "public" access in this case, since we
14164 // know by construction that we're calling from a derived class.
14165 if (CopyingBaseSubobject) {
14166 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14167 L != LEnd; ++L) {
14168 if (L.getAccess() == AS_protected)
14169 L.setAccess(AS_public);
14170 }
14171 }
14172
14173 // Create the nested-name-specifier that will be used to qualify the
14174 // reference to operator=; this is required to suppress the virtual
14175 // call mechanism.
14176 CXXScopeSpec SS;
14177 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14178 SS.MakeTrivial(S.Context,
14179 NestedNameSpecifier::Create(S.Context, nullptr, false,
14180 CanonicalT),
14181 Loc);
14182
14183 // Create the reference to operator=.
14184 ExprResult OpEqualRef
14185 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14186 SS, /*TemplateKWLoc=*/SourceLocation(),
14187 /*FirstQualifierInScope=*/nullptr,
14188 OpLookup,
14189 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14190 /*SuppressQualifierCheck=*/true);
14191 if (OpEqualRef.isInvalid())
14192 return StmtError();
14193
14194 // Build the call to the assignment operator.
14195
14196 Expr *FromInst = From.build(S, Loc);
14197 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14198 OpEqualRef.getAs<Expr>(),
14199 Loc, FromInst, Loc);
14200 if (Call.isInvalid())
14201 return StmtError();
14202
14203 // If we built a call to a trivial 'operator=' while copying an array,
14204 // bail out. We'll replace the whole shebang with a memcpy.
14205 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14206 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14207 return StmtResult((Stmt*)nullptr);
14208
14209 // Convert to an expression-statement, and clean up any produced
14210 // temporaries.
14211 return S.ActOnExprStmt(Call);
14212 }
14213
14214 // - if the subobject is of scalar type, the built-in assignment
14215 // operator is used.
14216 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14217 if (!ArrayTy) {
14218 ExprResult Assignment = S.CreateBuiltinBinOp(
14219 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14220 if (Assignment.isInvalid())
14221 return StmtError();
14222 return S.ActOnExprStmt(Assignment);
14223 }
14224
14225 // - if the subobject is an array, each element is assigned, in the
14226 // manner appropriate to the element type;
14227
14228 // Construct a loop over the array bounds, e.g.,
14229 //
14230 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14231 //
14232 // that will copy each of the array elements.
14233 QualType SizeType = S.Context.getSizeType();
14234
14235 // Create the iteration variable.
14236 IdentifierInfo *IterationVarName = nullptr;
14237 {
14238 SmallString<8> Str;
14239 llvm::raw_svector_ostream OS(Str);
14240 OS << "__i" << Depth;
14241 IterationVarName = &S.Context.Idents.get(OS.str());
14242 }
14243 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14244 IterationVarName, SizeType,
14245 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14246 SC_None);
14247
14248 // Initialize the iteration variable to zero.
14249 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14250 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14251
14252 // Creates a reference to the iteration variable.
14253 RefBuilder IterationVarRef(IterationVar, SizeType);
14254 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14255
14256 // Create the DeclStmt that holds the iteration variable.
14257 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14258
14259 // Subscript the "from" and "to" expressions with the iteration variable.
14260 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14261 MoveCastBuilder FromIndexMove(FromIndexCopy);
14262 const ExprBuilder *FromIndex;
14263 if (Copying)
14264 FromIndex = &FromIndexCopy;
14265 else
14266 FromIndex = &FromIndexMove;
14267
14268 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14269
14270 // Build the copy/move for an individual element of the array.
14271 StmtResult Copy =
14273 ToIndex, *FromIndex, CopyingBaseSubobject,
14274 Copying, Depth + 1);
14275 // Bail out if copying fails or if we determined that we should use memcpy.
14276 if (Copy.isInvalid() || !Copy.get())
14277 return Copy;
14278
14279 // Create the comparison against the array bound.
14280 llvm::APInt Upper
14281 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14282 Expr *Comparison = BinaryOperator::Create(
14283 S.Context, IterationVarRefRVal.build(S, Loc),
14284 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14287
14288 // Create the pre-increment of the iteration variable. We can determine
14289 // whether the increment will overflow based on the value of the array
14290 // bound.
14291 Expr *Increment = UnaryOperator::Create(
14292 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14293 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14294
14295 // Construct the loop that copies all elements of this array.
14296 return S.ActOnForStmt(
14297 Loc, Loc, InitStmt,
14298 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14299 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14300}
14301
14302static StmtResult
14304 const ExprBuilder &To, const ExprBuilder &From,
14305 bool CopyingBaseSubobject, bool Copying) {
14306 // Maybe we should use a memcpy?
14307 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14308 T.isTriviallyCopyableType(S.Context))
14309 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14310
14311 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14312 CopyingBaseSubobject,
14313 Copying, 0));
14314
14315 // If we ended up picking a trivial assignment operator for an array of a
14316 // non-trivially-copyable class type, just emit a memcpy.
14317 if (!Result.isInvalid() && !Result.get())
14318 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14319
14320 return Result;
14321}
14322
14324 // Note: The following rules are largely analoguous to the copy
14325 // constructor rules. Note that virtual bases are not taken into account
14326 // for determining the argument type of the operator. Note also that
14327 // operators taking an object instead of a reference are allowed.
14328 assert(ClassDecl->needsImplicitCopyAssignment());
14329
14330 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14331 if (DSM.isAlreadyBeingDeclared())
14332 return nullptr;
14333
14334 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14335 LangAS AS = getDefaultCXXMethodAddrSpace();
14336 if (AS != LangAS::Default)
14337 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14338 QualType RetType = Context.getLValueReferenceType(ArgType);
14339 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14340 if (Const)
14341 ArgType = ArgType.withConst();
14342
14343 ArgType = Context.getLValueReferenceType(ArgType);
14344
14345 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14346 CXXCopyAssignment,
14347 Const);
14348
14349 // An implicitly-declared copy assignment operator is an inline public
14350 // member of its class.
14351 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14352 SourceLocation ClassLoc = ClassDecl->getLocation();
14353 DeclarationNameInfo NameInfo(Name, ClassLoc);
14354 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14355 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14356 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14357 getCurFPFeatures().isFPConstrained(),
14358 /*isInline=*/true,
14359 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14360 SourceLocation());
14361 CopyAssignment->setAccess(AS_public);
14362 CopyAssignment->setDefaulted();
14363 CopyAssignment->setImplicit();
14364
14365 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14366
14367 if (getLangOpts().CUDA)
14368 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14369 CopyAssignment,
14370 /* ConstRHS */ Const,
14371 /* Diagnose */ false);
14372
14373 // Add the parameter to the operator.
14374 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14375 ClassLoc, ClassLoc,
14376 /*Id=*/nullptr, ArgType,
14377 /*TInfo=*/nullptr, SC_None,
14378 nullptr);
14379 CopyAssignment->setParams(FromParam);
14380
14381 CopyAssignment->setTrivial(
14383 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14384 : ClassDecl->hasTrivialCopyAssignment());
14385
14386 // Note that we have added this copy-assignment operator.
14387 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14388
14389 Scope *S = getScopeForContext(ClassDecl);
14390 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14391
14392 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14394 SetDeclDeleted(CopyAssignment, ClassLoc);
14395 }
14396
14397 if (S)
14398 PushOnScopeChains(CopyAssignment, S, false);
14399 ClassDecl->addDecl(CopyAssignment);
14400
14401 return CopyAssignment;
14402}
14403
14404/// Diagnose an implicit copy operation for a class which is odr-used, but
14405/// which is deprecated because the class has a user-declared copy constructor,
14406/// copy assignment operator, or destructor.
14408 assert(CopyOp->isImplicit());
14409
14410 CXXRecordDecl *RD = CopyOp->getParent();
14411 CXXMethodDecl *UserDeclaredOperation = nullptr;
14412
14413 // In Microsoft mode, assignment operations don't affect constructors and
14414 // vice versa.
14415 if (RD->hasUserDeclaredDestructor()) {
14416 UserDeclaredOperation = RD->getDestructor();
14417 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14419 !S.getLangOpts().MSVCCompat) {
14420 // Find any user-declared copy constructor.
14421 for (auto *I : RD->ctors()) {
14422 if (I->isCopyConstructor()) {
14423 UserDeclaredOperation = I;
14424 break;
14425 }
14426 }
14427 assert(UserDeclaredOperation);
14428 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14430 !S.getLangOpts().MSVCCompat) {
14431 // Find any user-declared move assignment operator.
14432 for (auto *I : RD->methods()) {
14433 if (I->isCopyAssignmentOperator()) {
14434 UserDeclaredOperation = I;
14435 break;
14436 }
14437 }
14438 assert(UserDeclaredOperation);
14439 }
14440
14441 if (UserDeclaredOperation) {
14442 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14443 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14444 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14445 unsigned DiagID =
14446 (UDOIsUserProvided && UDOIsDestructor)
14447 ? diag::warn_deprecated_copy_with_user_provided_dtor
14448 : (UDOIsUserProvided && !UDOIsDestructor)
14449 ? diag::warn_deprecated_copy_with_user_provided_copy
14450 : (!UDOIsUserProvided && UDOIsDestructor)
14451 ? diag::warn_deprecated_copy_with_dtor
14452 : diag::warn_deprecated_copy;
14453 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14454 << RD << IsCopyAssignment;
14455 }
14456}
14457
14459 CXXMethodDecl *CopyAssignOperator) {
14460 assert((CopyAssignOperator->isDefaulted() &&
14461 CopyAssignOperator->isOverloadedOperator() &&
14462 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14463 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14464 !CopyAssignOperator->isDeleted()) &&
14465 "DefineImplicitCopyAssignment called for wrong function");
14466 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14467 return;
14468
14469 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14470 if (ClassDecl->isInvalidDecl()) {
14471 CopyAssignOperator->setInvalidDecl();
14472 return;
14473 }
14474
14475 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14476
14477 // The exception specification is needed because we are defining the
14478 // function.
14479 ResolveExceptionSpec(CurrentLocation,
14480 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14481
14482 // Add a context note for diagnostics produced after this point.
14483 Scope.addContextNote(CurrentLocation);
14484
14485 // C++11 [class.copy]p18:
14486 // The [definition of an implicitly declared copy assignment operator] is
14487 // deprecated if the class has a user-declared copy constructor or a
14488 // user-declared destructor.
14489 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14490 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14491
14492 // C++0x [class.copy]p30:
14493 // The implicitly-defined or explicitly-defaulted copy assignment operator
14494 // for a non-union class X performs memberwise copy assignment of its
14495 // subobjects. The direct base classes of X are assigned first, in the
14496 // order of their declaration in the base-specifier-list, and then the
14497 // immediate non-static data members of X are assigned, in the order in
14498 // which they were declared in the class definition.
14499
14500 // The statements that form the synthesized function body.
14501 SmallVector<Stmt*, 8> Statements;
14502
14503 // The parameter for the "other" object, which we are copying from.
14504 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14505 Qualifiers OtherQuals = Other->getType().getQualifiers();
14506 QualType OtherRefType = Other->getType();
14507 if (const LValueReferenceType *OtherRef
14508 = OtherRefType->getAs<LValueReferenceType>()) {
14509 OtherRefType = OtherRef->getPointeeType();
14510 OtherQuals = OtherRefType.getQualifiers();
14511 }
14512
14513 // Our location for everything implicitly-generated.
14514 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14515 ? CopyAssignOperator->getEndLoc()
14516 : CopyAssignOperator->getLocation();
14517
14518 // Builds a DeclRefExpr for the "other" object.
14519 RefBuilder OtherRef(Other, OtherRefType);
14520
14521 // Builds the "this" pointer.
14522 ThisBuilder This;
14523
14524 // Assign base classes.
14525 bool Invalid = false;
14526 for (auto &Base : ClassDecl->bases()) {
14527 // Form the assignment:
14528 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14529 QualType BaseType = Base.getType().getUnqualifiedType();
14530 if (!BaseType->isRecordType()) {
14531 Invalid = true;
14532 continue;
14533 }
14534
14535 CXXCastPath BasePath;
14536 BasePath.push_back(&Base);
14537
14538 // Construct the "from" expression, which is an implicit cast to the
14539 // appropriately-qualified base type.
14540 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14541 VK_LValue, BasePath);
14542
14543 // Dereference "this".
14544 DerefBuilder DerefThis(This);
14545 CastBuilder To(DerefThis,
14546 Context.getQualifiedType(
14547 BaseType, CopyAssignOperator->getMethodQualifiers()),
14548 VK_LValue, BasePath);
14549
14550 // Build the copy.
14551 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14552 To, From,
14553 /*CopyingBaseSubobject=*/true,
14554 /*Copying=*/true);
14555 if (Copy.isInvalid()) {
14556 CopyAssignOperator->setInvalidDecl();
14557 return;
14558 }
14559
14560 // Success! Record the copy.
14561 Statements.push_back(Copy.getAs<Expr>());
14562 }
14563
14564 // Assign non-static members.
14565 for (auto *Field : ClassDecl->fields()) {
14566 // FIXME: We should form some kind of AST representation for the implied
14567 // memcpy in a union copy operation.
14568 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14569 continue;
14570
14571 if (Field->isInvalidDecl()) {
14572 Invalid = true;
14573 continue;
14574 }
14575
14576 // Check for members of reference type; we can't copy those.
14577 if (Field->getType()->isReferenceType()) {
14578 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14579 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14580 Diag(Field->getLocation(), diag::note_declared_at);
14581 Invalid = true;
14582 continue;
14583 }
14584
14585 // Check for members of const-qualified, non-class type.
14586 QualType BaseType = Context.getBaseElementType(Field->getType());
14587 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14588 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14589 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14590 Diag(Field->getLocation(), diag::note_declared_at);
14591 Invalid = true;
14592 continue;
14593 }
14594
14595 // Suppress assigning zero-width bitfields.
14596 if (Field->isZeroLengthBitField(Context))
14597 continue;
14598
14599 QualType FieldType = Field->getType().getNonReferenceType();
14600 if (FieldType->isIncompleteArrayType()) {
14601 assert(ClassDecl->hasFlexibleArrayMember() &&
14602 "Incomplete array type is not valid");
14603 continue;
14604 }
14605
14606 // Build references to the field in the object we're copying from and to.
14607 CXXScopeSpec SS; // Intentionally empty
14608 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14609 LookupMemberName);
14610 MemberLookup.addDecl(Field);
14611 MemberLookup.resolveKind();
14612
14613 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14614
14615 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14616
14617 // Build the copy of this field.
14618 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14619 To, From,
14620 /*CopyingBaseSubobject=*/false,
14621 /*Copying=*/true);
14622 if (Copy.isInvalid()) {
14623 CopyAssignOperator->setInvalidDecl();
14624 return;
14625 }
14626
14627 // Success! Record the copy.
14628 Statements.push_back(Copy.getAs<Stmt>());
14629 }
14630
14631 if (!Invalid) {
14632 // Add a "return *this;"
14633 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14634
14635 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14636 if (Return.isInvalid())
14637 Invalid = true;
14638 else
14639 Statements.push_back(Return.getAs<Stmt>());
14640 }
14641
14642 if (Invalid) {
14643 CopyAssignOperator->setInvalidDecl();
14644 return;
14645 }
14646
14647 StmtResult Body;
14648 {
14649 CompoundScopeRAII CompoundScope(*this);
14650 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14651 /*isStmtExpr=*/false);
14652 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14653 }
14654 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14655 CopyAssignOperator->markUsed(Context);
14656
14657 if (ASTMutationListener *L = getASTMutationListener()) {
14658 L->CompletedImplicitDefinition(CopyAssignOperator);
14659 }
14660}
14661
14663 assert(ClassDecl->needsImplicitMoveAssignment());
14664
14665 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14666 if (DSM.isAlreadyBeingDeclared())
14667 return nullptr;
14668
14669 // Note: The following rules are largely analoguous to the move
14670 // constructor rules.
14671
14672 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14673 LangAS AS = getDefaultCXXMethodAddrSpace();
14674 if (AS != LangAS::Default)
14675 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14676 QualType RetType = Context.getLValueReferenceType(ArgType);
14677 ArgType = Context.getRValueReferenceType(ArgType);
14678
14679 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14680 CXXMoveAssignment,
14681 false);
14682
14683 // An implicitly-declared move assignment operator is an inline public
14684 // member of its class.
14685 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14686 SourceLocation ClassLoc = ClassDecl->getLocation();
14687 DeclarationNameInfo NameInfo(Name, ClassLoc);
14688 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14689 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14690 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14691 getCurFPFeatures().isFPConstrained(),
14692 /*isInline=*/true,
14693 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14694 SourceLocation());
14695 MoveAssignment->setAccess(AS_public);
14696 MoveAssignment->setDefaulted();
14697 MoveAssignment->setImplicit();
14698
14699 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14700
14701 if (getLangOpts().CUDA)
14702 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14703 MoveAssignment,
14704 /* ConstRHS */ false,
14705 /* Diagnose */ false);
14706
14707 // Add the parameter to the operator.
14708 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14709 ClassLoc, ClassLoc,
14710 /*Id=*/nullptr, ArgType,
14711 /*TInfo=*/nullptr, SC_None,
14712 nullptr);
14713 MoveAssignment->setParams(FromParam);
14714
14715 MoveAssignment->setTrivial(
14717 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14718 : ClassDecl->hasTrivialMoveAssignment());
14719
14720 // Note that we have added this copy-assignment operator.
14721 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14722
14723 Scope *S = getScopeForContext(ClassDecl);
14724 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14725
14726 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14728 SetDeclDeleted(MoveAssignment, ClassLoc);
14729 }
14730
14731 if (S)
14732 PushOnScopeChains(MoveAssignment, S, false);
14733 ClassDecl->addDecl(MoveAssignment);
14734
14735 return MoveAssignment;
14736}
14737
14738/// Check if we're implicitly defining a move assignment operator for a class
14739/// with virtual bases. Such a move assignment might move-assign the virtual
14740/// base multiple times.
14742 SourceLocation CurrentLocation) {
14743 assert(!Class->isDependentContext() && "should not define dependent move");
14744
14745 // Only a virtual base could get implicitly move-assigned multiple times.
14746 // Only a non-trivial move assignment can observe this. We only want to
14747 // diagnose if we implicitly define an assignment operator that assigns
14748 // two base classes, both of which move-assign the same virtual base.
14749 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14750 Class->getNumBases() < 2)
14751 return;
14752
14754 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14755 VBaseMap VBases;
14756
14757 for (auto &BI : Class->bases()) {
14758 Worklist.push_back(&BI);
14759 while (!Worklist.empty()) {
14760 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14761 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14762
14763 // If the base has no non-trivial move assignment operators,
14764 // we don't care about moves from it.
14765 if (!Base->hasNonTrivialMoveAssignment())
14766 continue;
14767
14768 // If there's nothing virtual here, skip it.
14769 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14770 continue;
14771
14772 // If we're not actually going to call a move assignment for this base,
14773 // or the selected move assignment is trivial, skip it.
14776 /*ConstArg*/false, /*VolatileArg*/false,
14777 /*RValueThis*/true, /*ConstThis*/false,
14778 /*VolatileThis*/false);
14779 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14781 continue;
14782
14783 if (BaseSpec->isVirtual()) {
14784 // We're going to move-assign this virtual base, and its move
14785 // assignment operator is not trivial. If this can happen for
14786 // multiple distinct direct bases of Class, diagnose it. (If it
14787 // only happens in one base, we'll diagnose it when synthesizing
14788 // that base class's move assignment operator.)
14789 CXXBaseSpecifier *&Existing =
14790 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14791 .first->second;
14792 if (Existing && Existing != &BI) {
14793 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14794 << Class << Base;
14795 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14796 << (Base->getCanonicalDecl() ==
14798 << Base << Existing->getType() << Existing->getSourceRange();
14799 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14800 << (Base->getCanonicalDecl() ==
14801 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14802 << Base << BI.getType() << BaseSpec->getSourceRange();
14803
14804 // Only diagnose each vbase once.
14805 Existing = nullptr;
14806 }
14807 } else {
14808 // Only walk over bases that have defaulted move assignment operators.
14809 // We assume that any user-provided move assignment operator handles
14810 // the multiple-moves-of-vbase case itself somehow.
14811 if (!SMOR.getMethod()->isDefaulted())
14812 continue;
14813
14814 // We're going to move the base classes of Base. Add them to the list.
14815 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14816 }
14817 }
14818 }
14819}
14820
14822 CXXMethodDecl *MoveAssignOperator) {
14823 assert((MoveAssignOperator->isDefaulted() &&
14824 MoveAssignOperator->isOverloadedOperator() &&
14825 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14826 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14827 !MoveAssignOperator->isDeleted()) &&
14828 "DefineImplicitMoveAssignment called for wrong function");
14829 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14830 return;
14831
14832 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14833 if (ClassDecl->isInvalidDecl()) {
14834 MoveAssignOperator->setInvalidDecl();
14835 return;
14836 }
14837
14838 // C++0x [class.copy]p28:
14839 // The implicitly-defined or move assignment operator for a non-union class
14840 // X performs memberwise move assignment of its subobjects. The direct base
14841 // classes of X are assigned first, in the order of their declaration in the
14842 // base-specifier-list, and then the immediate non-static data members of X
14843 // are assigned, in the order in which they were declared in the class
14844 // definition.
14845
14846 // Issue a warning if our implicit move assignment operator will move
14847 // from a virtual base more than once.
14848 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14849
14850 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14851
14852 // The exception specification is needed because we are defining the
14853 // function.
14854 ResolveExceptionSpec(CurrentLocation,
14855 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14856
14857 // Add a context note for diagnostics produced after this point.
14858 Scope.addContextNote(CurrentLocation);
14859
14860 // The statements that form the synthesized function body.
14861 SmallVector<Stmt*, 8> Statements;
14862
14863 // The parameter for the "other" object, which we are move from.
14864 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14865 QualType OtherRefType =
14866 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14867
14868 // Our location for everything implicitly-generated.
14869 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14870 ? MoveAssignOperator->getEndLoc()
14871 : MoveAssignOperator->getLocation();
14872
14873 // Builds a reference to the "other" object.
14874 RefBuilder OtherRef(Other, OtherRefType);
14875 // Cast to rvalue.
14876 MoveCastBuilder MoveOther(OtherRef);
14877
14878 // Builds the "this" pointer.
14879 ThisBuilder This;
14880
14881 // Assign base classes.
14882 bool Invalid = false;
14883 for (auto &Base : ClassDecl->bases()) {
14884 // C++11 [class.copy]p28:
14885 // It is unspecified whether subobjects representing virtual base classes
14886 // are assigned more than once by the implicitly-defined copy assignment
14887 // operator.
14888 // FIXME: Do not assign to a vbase that will be assigned by some other base
14889 // class. For a move-assignment, this can result in the vbase being moved
14890 // multiple times.
14891
14892 // Form the assignment:
14893 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14894 QualType BaseType = Base.getType().getUnqualifiedType();
14895 if (!BaseType->isRecordType()) {
14896 Invalid = true;
14897 continue;
14898 }
14899
14900 CXXCastPath BasePath;
14901 BasePath.push_back(&Base);
14902
14903 // Construct the "from" expression, which is an implicit cast to the
14904 // appropriately-qualified base type.
14905 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14906
14907 // Dereference "this".
14908 DerefBuilder DerefThis(This);
14909
14910 // Implicitly cast "this" to the appropriately-qualified base type.
14911 CastBuilder To(DerefThis,
14912 Context.getQualifiedType(
14913 BaseType, MoveAssignOperator->getMethodQualifiers()),
14914 VK_LValue, BasePath);
14915
14916 // Build the move.
14917 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14918 To, From,
14919 /*CopyingBaseSubobject=*/true,
14920 /*Copying=*/false);
14921 if (Move.isInvalid()) {
14922 MoveAssignOperator->setInvalidDecl();
14923 return;
14924 }
14925
14926 // Success! Record the move.
14927 Statements.push_back(Move.getAs<Expr>());
14928 }
14929
14930 // Assign non-static members.
14931 for (auto *Field : ClassDecl->fields()) {
14932 // FIXME: We should form some kind of AST representation for the implied
14933 // memcpy in a union copy operation.
14934 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14935 continue;
14936
14937 if (Field->isInvalidDecl()) {
14938 Invalid = true;
14939 continue;
14940 }
14941
14942 // Check for members of reference type; we can't move those.
14943 if (Field->getType()->isReferenceType()) {
14944 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14945 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14946 Diag(Field->getLocation(), diag::note_declared_at);
14947 Invalid = true;
14948 continue;
14949 }
14950
14951 // Check for members of const-qualified, non-class type.
14952 QualType BaseType = Context.getBaseElementType(Field->getType());
14953 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14954 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14955 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14956 Diag(Field->getLocation(), diag::note_declared_at);
14957 Invalid = true;
14958 continue;
14959 }
14960
14961 // Suppress assigning zero-width bitfields.
14962 if (Field->isZeroLengthBitField(Context))
14963 continue;
14964
14965 QualType FieldType = Field->getType().getNonReferenceType();
14966 if (FieldType->isIncompleteArrayType()) {
14967 assert(ClassDecl->hasFlexibleArrayMember() &&
14968 "Incomplete array type is not valid");
14969 continue;
14970 }
14971
14972 // Build references to the field in the object we're copying from and to.
14973 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14974 LookupMemberName);
14975 MemberLookup.addDecl(Field);
14976 MemberLookup.resolveKind();
14977 MemberBuilder From(MoveOther, OtherRefType,
14978 /*IsArrow=*/false, MemberLookup);
14979 MemberBuilder To(This, getCurrentThisType(),
14980 /*IsArrow=*/true, MemberLookup);
14981
14982 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14983 "Member reference with rvalue base must be rvalue except for reference "
14984 "members, which aren't allowed for move assignment.");
14985
14986 // Build the move of this field.
14987 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14988 To, From,
14989 /*CopyingBaseSubobject=*/false,
14990 /*Copying=*/false);
14991 if (Move.isInvalid()) {
14992 MoveAssignOperator->setInvalidDecl();
14993 return;
14994 }
14995
14996 // Success! Record the copy.
14997 Statements.push_back(Move.getAs<Stmt>());
14998 }
14999
15000 if (!Invalid) {
15001 // Add a "return *this;"
15002 ExprResult ThisObj =
15003 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15004
15005 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15006 if (Return.isInvalid())
15007 Invalid = true;
15008 else
15009 Statements.push_back(Return.getAs<Stmt>());
15010 }
15011
15012 if (Invalid) {
15013 MoveAssignOperator->setInvalidDecl();
15014 return;
15015 }
15016
15017 StmtResult Body;
15018 {
15019 CompoundScopeRAII CompoundScope(*this);
15020 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15021 /*isStmtExpr=*/false);
15022 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15023 }
15024 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15025 MoveAssignOperator->markUsed(Context);
15026
15027 if (ASTMutationListener *L = getASTMutationListener()) {
15028 L->CompletedImplicitDefinition(MoveAssignOperator);
15029 }
15030}
15031
15033 CXXRecordDecl *ClassDecl) {
15034 // C++ [class.copy]p4:
15035 // If the class definition does not explicitly declare a copy
15036 // constructor, one is declared implicitly.
15037 assert(ClassDecl->needsImplicitCopyConstructor());
15038
15039 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15040 if (DSM.isAlreadyBeingDeclared())
15041 return nullptr;
15042
15043 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15044 QualType ArgType = ClassType;
15045 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15046 if (Const)
15047 ArgType = ArgType.withConst();
15048
15049 LangAS AS = getDefaultCXXMethodAddrSpace();
15050 if (AS != LangAS::Default)
15051 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15052
15053 ArgType = Context.getLValueReferenceType(ArgType);
15054
15055 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15056 CXXCopyConstructor,
15057 Const);
15058
15059 DeclarationName Name
15061 Context.getCanonicalType(ClassType));
15062 SourceLocation ClassLoc = ClassDecl->getLocation();
15063 DeclarationNameInfo NameInfo(Name, ClassLoc);
15064
15065 // An implicitly-declared copy constructor is an inline public
15066 // member of its class.
15068 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15069 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15070 /*isInline=*/true,
15071 /*isImplicitlyDeclared=*/true,
15072 Constexpr ? ConstexprSpecKind::Constexpr
15073 : ConstexprSpecKind::Unspecified);
15074 CopyConstructor->setAccess(AS_public);
15075 CopyConstructor->setDefaulted();
15076
15077 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15078
15079 if (getLangOpts().CUDA)
15080 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15081 CopyConstructor,
15082 /* ConstRHS */ Const,
15083 /* Diagnose */ false);
15084
15085 // During template instantiation of special member functions we need a
15086 // reliable TypeSourceInfo for the parameter types in order to allow functions
15087 // to be substituted.
15088 TypeSourceInfo *TSI = nullptr;
15089 if (inTemplateInstantiation() && ClassDecl->isLambda())
15090 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15091
15092 // Add the parameter to the constructor.
15093 ParmVarDecl *FromParam =
15094 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15095 /*IdentifierInfo=*/nullptr, ArgType,
15096 /*TInfo=*/TSI, SC_None, nullptr);
15097 CopyConstructor->setParams(FromParam);
15098
15099 CopyConstructor->setTrivial(
15101 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15102 : ClassDecl->hasTrivialCopyConstructor());
15103
15104 CopyConstructor->setTrivialForCall(
15105 ClassDecl->hasAttr<TrivialABIAttr>() ||
15107 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15108 TAH_ConsiderTrivialABI)
15109 : ClassDecl->hasTrivialCopyConstructorForCall()));
15110
15111 // Note that we have declared this constructor.
15112 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15113
15114 Scope *S = getScopeForContext(ClassDecl);
15115 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15116
15117 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15119 SetDeclDeleted(CopyConstructor, ClassLoc);
15120 }
15121
15122 if (S)
15123 PushOnScopeChains(CopyConstructor, S, false);
15124 ClassDecl->addDecl(CopyConstructor);
15125
15126 return CopyConstructor;
15127}
15128
15130 CXXConstructorDecl *CopyConstructor) {
15131 assert((CopyConstructor->isDefaulted() &&
15132 CopyConstructor->isCopyConstructor() &&
15133 !CopyConstructor->doesThisDeclarationHaveABody() &&
15134 !CopyConstructor->isDeleted()) &&
15135 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15136 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15137 return;
15138
15139 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15140 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15141
15142 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15143
15144 // The exception specification is needed because we are defining the
15145 // function.
15146 ResolveExceptionSpec(CurrentLocation,
15147 CopyConstructor->getType()->castAs<FunctionProtoType>());
15148 MarkVTableUsed(CurrentLocation, ClassDecl);
15149
15150 // Add a context note for diagnostics produced after this point.
15151 Scope.addContextNote(CurrentLocation);
15152
15153 // C++11 [class.copy]p7:
15154 // The [definition of an implicitly declared copy constructor] is
15155 // deprecated if the class has a user-declared copy assignment operator
15156 // or a user-declared destructor.
15157 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15158 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15159
15160 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15161 CopyConstructor->setInvalidDecl();
15162 } else {
15163 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15164 ? CopyConstructor->getEndLoc()
15165 : CopyConstructor->getLocation();
15166 Sema::CompoundScopeRAII CompoundScope(*this);
15167 CopyConstructor->setBody(
15168 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15169 CopyConstructor->markUsed(Context);
15170 }
15171
15172 if (ASTMutationListener *L = getASTMutationListener()) {
15173 L->CompletedImplicitDefinition(CopyConstructor);
15174 }
15175}
15176
15178 CXXRecordDecl *ClassDecl) {
15179 assert(ClassDecl->needsImplicitMoveConstructor());
15180
15181 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15182 if (DSM.isAlreadyBeingDeclared())
15183 return nullptr;
15184
15185 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15186
15187 QualType ArgType = ClassType;
15188 LangAS AS = getDefaultCXXMethodAddrSpace();
15189 if (AS != LangAS::Default)
15190 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15191 ArgType = Context.getRValueReferenceType(ArgType);
15192
15193 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15194 CXXMoveConstructor,
15195 false);
15196
15197 DeclarationName Name
15199 Context.getCanonicalType(ClassType));
15200 SourceLocation ClassLoc = ClassDecl->getLocation();
15201 DeclarationNameInfo NameInfo(Name, ClassLoc);
15202
15203 // C++11 [class.copy]p11:
15204 // An implicitly-declared copy/move constructor is an inline public
15205 // member of its class.
15207 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15208 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15209 /*isInline=*/true,
15210 /*isImplicitlyDeclared=*/true,
15211 Constexpr ? ConstexprSpecKind::Constexpr
15212 : ConstexprSpecKind::Unspecified);
15213 MoveConstructor->setAccess(AS_public);
15214 MoveConstructor->setDefaulted();
15215
15216 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15217
15218 if (getLangOpts().CUDA)
15219 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15220 MoveConstructor,
15221 /* ConstRHS */ false,
15222 /* Diagnose */ false);
15223
15224 // Add the parameter to the constructor.
15225 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15226 ClassLoc, ClassLoc,
15227 /*IdentifierInfo=*/nullptr,
15228 ArgType, /*TInfo=*/nullptr,
15229 SC_None, nullptr);
15230 MoveConstructor->setParams(FromParam);
15231
15232 MoveConstructor->setTrivial(
15234 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15235 : ClassDecl->hasTrivialMoveConstructor());
15236
15237 MoveConstructor->setTrivialForCall(
15238 ClassDecl->hasAttr<TrivialABIAttr>() ||
15240 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15241 TAH_ConsiderTrivialABI)
15242 : ClassDecl->hasTrivialMoveConstructorForCall()));
15243
15244 // Note that we have declared this constructor.
15245 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15246
15247 Scope *S = getScopeForContext(ClassDecl);
15248 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15249
15250 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15252 SetDeclDeleted(MoveConstructor, ClassLoc);
15253 }
15254
15255 if (S)
15256 PushOnScopeChains(MoveConstructor, S, false);
15257 ClassDecl->addDecl(MoveConstructor);
15258
15259 return MoveConstructor;
15260}
15261
15263 CXXConstructorDecl *MoveConstructor) {
15264 assert((MoveConstructor->isDefaulted() &&
15265 MoveConstructor->isMoveConstructor() &&
15266 !MoveConstructor->doesThisDeclarationHaveABody() &&
15267 !MoveConstructor->isDeleted()) &&
15268 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15269 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15270 return;
15271
15272 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15273 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15274
15275 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15276
15277 // The exception specification is needed because we are defining the
15278 // function.
15279 ResolveExceptionSpec(CurrentLocation,
15280 MoveConstructor->getType()->castAs<FunctionProtoType>());
15281 MarkVTableUsed(CurrentLocation, ClassDecl);
15282
15283 // Add a context note for diagnostics produced after this point.
15284 Scope.addContextNote(CurrentLocation);
15285
15286 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15287 MoveConstructor->setInvalidDecl();
15288 } else {
15289 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15290 ? MoveConstructor->getEndLoc()
15291 : MoveConstructor->getLocation();
15292 Sema::CompoundScopeRAII CompoundScope(*this);
15293 MoveConstructor->setBody(ActOnCompoundStmt(
15294 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15295 MoveConstructor->markUsed(Context);
15296 }
15297
15298 if (ASTMutationListener *L = getASTMutationListener()) {
15299 L->CompletedImplicitDefinition(MoveConstructor);
15300 }
15301}
15302
15304 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15305}
15306
15308 SourceLocation CurrentLocation,
15309 CXXConversionDecl *Conv) {
15310 SynthesizedFunctionScope Scope(*this, Conv);
15311 assert(!Conv->getReturnType()->isUndeducedType());
15312
15313 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15314 CallingConv CC =
15315 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15316
15317 CXXRecordDecl *Lambda = Conv->getParent();
15318 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15319 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15320
15321 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15322 CallOp = InstantiateFunctionDeclaration(
15323 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15324 if (!CallOp)
15325 return;
15326
15327 Invoker = InstantiateFunctionDeclaration(
15328 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15329 if (!Invoker)
15330 return;
15331 }
15332
15333 if (CallOp->isInvalidDecl())
15334 return;
15335
15336 // Mark the call operator referenced (and add to pending instantiations
15337 // if necessary).
15338 // For both the conversion and static-invoker template specializations
15339 // we construct their body's in this function, so no need to add them
15340 // to the PendingInstantiations.
15341 MarkFunctionReferenced(CurrentLocation, CallOp);
15342
15343 // Fill in the __invoke function with a dummy implementation. IR generation
15344 // will fill in the actual details. Update its type in case it contained
15345 // an 'auto'.
15346 Invoker->markUsed(Context);
15347 Invoker->setReferenced();
15348 Invoker->setType(Conv->getReturnType()->getPointeeType());
15349 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15350
15351 // Construct the body of the conversion function { return __invoke; }.
15352 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15353 VK_LValue, Conv->getLocation());
15354 assert(FunctionRef && "Can't refer to __invoke function?");
15355 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15356 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15357 Conv->getLocation(), Conv->getLocation()));
15358 Conv->markUsed(Context);
15359 Conv->setReferenced();
15360
15361 if (ASTMutationListener *L = getASTMutationListener()) {
15362 L->CompletedImplicitDefinition(Conv);
15363 L->CompletedImplicitDefinition(Invoker);
15364 }
15365}
15366
15367
15368
15370 SourceLocation CurrentLocation,
15371 CXXConversionDecl *Conv)
15372{
15373 assert(!Conv->getParent()->isGenericLambda());
15374
15375 SynthesizedFunctionScope Scope(*this, Conv);
15376
15377 // Copy-initialize the lambda object as needed to capture it.
15378 Expr *This = ActOnCXXThis(CurrentLocation).get();
15379 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15380
15381 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15382 Conv->getLocation(),
15383 Conv, DerefThis);
15384
15385 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15386 // behavior. Note that only the general conversion function does this
15387 // (since it's unusable otherwise); in the case where we inline the
15388 // block literal, it has block literal lifetime semantics.
15389 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15390 BuildBlock = ImplicitCastExpr::Create(
15391 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15392 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15393
15394 if (BuildBlock.isInvalid()) {
15395 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15396 Conv->setInvalidDecl();
15397 return;
15398 }
15399
15400 // Create the return statement that returns the block from the conversion
15401 // function.
15402 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15403 if (Return.isInvalid()) {
15404 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15405 Conv->setInvalidDecl();
15406 return;
15407 }
15408
15409 // Set the body of the conversion function.
15410 Stmt *ReturnS = Return.get();
15411 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15412 Conv->getLocation(), Conv->getLocation()));
15413 Conv->markUsed(Context);
15414
15415 // We're done; notify the mutation listener, if any.
15416 if (ASTMutationListener *L = getASTMutationListener()) {
15417 L->CompletedImplicitDefinition(Conv);
15418 }
15419}
15420
15421/// Determine whether the given list arguments contains exactly one
15422/// "real" (non-default) argument.
15424 switch (Args.size()) {
15425 case 0:
15426 return false;
15427
15428 default:
15429 if (!Args[1]->isDefaultArgument())
15430 return false;
15431
15432 LLVM_FALLTHROUGH;
15433 case 1:
15434 return !Args[0]->isDefaultArgument();
15435 }
15436
15437 return false;
15438}
15439
15442 NamedDecl *FoundDecl,
15443 CXXConstructorDecl *Constructor,
15444 MultiExprArg ExprArgs,
15445 bool HadMultipleCandidates,
15446 bool IsListInitialization,
15447 bool IsStdInitListInitialization,
15448 bool RequiresZeroInit,
15449 unsigned ConstructKind,
15450 SourceRange ParenRange) {
15451 bool Elidable = false;
15452
15453 // C++0x [class.copy]p34:
15454 // When certain criteria are met, an implementation is allowed to
15455 // omit the copy/move construction of a class object, even if the
15456 // copy/move constructor and/or destructor for the object have
15457 // side effects. [...]
15458 // - when a temporary class object that has not been bound to a
15459 // reference (12.2) would be copied/moved to a class object
15460 // with the same cv-unqualified type, the copy/move operation
15461 // can be omitted by constructing the temporary object
15462 // directly into the target of the omitted copy/move
15463 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15464 // FIXME: Converting constructors should also be accepted.
15465 // But to fix this, the logic that digs down into a CXXConstructExpr
15466 // to find the source object needs to handle it.
15467 // Right now it assumes the source object is passed directly as the
15468 // first argument.
15469 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15470 Expr *SubExpr = ExprArgs[0];
15471 // FIXME: Per above, this is also incorrect if we want to accept
15472 // converting constructors, as isTemporaryObject will
15473 // reject temporaries with different type from the
15474 // CXXRecord itself.
15475 Elidable = SubExpr->isTemporaryObject(
15476 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15477 }
15478
15479 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15480 FoundDecl, Constructor,
15481 Elidable, ExprArgs, HadMultipleCandidates,
15482 IsListInitialization,
15483 IsStdInitListInitialization, RequiresZeroInit,
15484 ConstructKind, ParenRange);
15485}
15486
15489 NamedDecl *FoundDecl,
15490 CXXConstructorDecl *Constructor,
15491 bool Elidable,
15492 MultiExprArg ExprArgs,
15493 bool HadMultipleCandidates,
15494 bool IsListInitialization,
15495 bool IsStdInitListInitialization,
15496 bool RequiresZeroInit,
15497 unsigned ConstructKind,
15498 SourceRange ParenRange) {
15499 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15500 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15501 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15502 return ExprError();
15503 }
15504
15505 return BuildCXXConstructExpr(
15506 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15507 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15508 RequiresZeroInit, ConstructKind, ParenRange);
15509}
15510
15511/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15512/// including handling of its default argument expressions.
15515 CXXConstructorDecl *Constructor,
15516 bool Elidable,
15517 MultiExprArg ExprArgs,
15518 bool HadMultipleCandidates,
15519 bool IsListInitialization,
15520 bool IsStdInitListInitialization,
15521 bool RequiresZeroInit,
15522 unsigned ConstructKind,
15523 SourceRange ParenRange) {
15524 assert(declaresSameEntity(
15525 Constructor->getParent(),
15526 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15527 "given constructor for wrong type");
15528 MarkFunctionReferenced(ConstructLoc, Constructor);
15529 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15530 return ExprError();
15531 if (getLangOpts().SYCLIsDevice &&
15532 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15533 return ExprError();
15534
15535 return CheckForImmediateInvocation(
15537 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15538 HadMultipleCandidates, IsListInitialization,
15539 IsStdInitListInitialization, RequiresZeroInit,
15540 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15541 ParenRange),
15542 Constructor);
15543}
15544
15546 assert(Field->hasInClassInitializer());
15547
15548 // If we already have the in-class initializer nothing needs to be done.
15549 if (Field->getInClassInitializer())
15550 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15551
15552 // If we might have already tried and failed to instantiate, don't try again.
15553 if (Field->isInvalidDecl())
15554 return ExprError();
15555
15556 // Maybe we haven't instantiated the in-class initializer. Go check the
15557 // pattern FieldDecl to see if it has one.
15558 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15559
15561 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15563 ClassPattern->lookup(Field->getDeclName());
15564
15565 FieldDecl *Pattern = nullptr;
15566 for (auto L : Lookup) {
15567 if (isa<FieldDecl>(L)) {
15568 Pattern = cast<FieldDecl>(L);
15569 break;
15570 }
15571 }
15572 assert(Pattern && "We must have set the Pattern!");
15573
15574 if (!Pattern->hasInClassInitializer() ||
15575 InstantiateInClassInitializer(Loc, Field, Pattern,
15576 getTemplateInstantiationArgs(Field))) {
15577 // Don't diagnose this again.
15578 Field->setInvalidDecl();
15579 return ExprError();
15580 }
15581 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15582 }
15583
15584 // DR1351:
15585 // If the brace-or-equal-initializer of a non-static data member
15586 // invokes a defaulted default constructor of its class or of an
15587 // enclosing class in a potentially evaluated subexpression, the
15588 // program is ill-formed.
15589 //
15590 // This resolution is unworkable: the exception specification of the
15591 // default constructor can be needed in an unevaluated context, in
15592 // particular, in the operand of a noexcept-expression, and we can be
15593 // unable to compute an exception specification for an enclosed class.
15594 //
15595 // Any attempt to resolve the exception specification of a defaulted default
15596 // constructor before the initializer is lexically complete will ultimately
15597 // come here at which point we can diagnose it.
15598 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15599 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15600 << OutermostClass << Field;
15601 Diag(Field->getEndLoc(),
15602 diag::note_default_member_initializer_not_yet_parsed);
15603 // Recover by marking the field invalid, unless we're in a SFINAE context.
15604 if (!isSFINAEContext())
15605 Field->setInvalidDecl();
15606 return ExprError();
15607}
15608
15610 if (VD->isInvalidDecl()) return;
15611 // If initializing the variable failed, don't also diagnose problems with
15612 // the destructor, they're likely related.
15613 if (VD->getInit() && VD->getInit()->containsErrors())
15614 return;
15615
15616 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15617 if (ClassDecl->isInvalidDecl()) return;
15618 if (ClassDecl->hasIrrelevantDestructor()) return;
15619 if (ClassDecl->isDependentContext()) return;
15620
15621 if (VD->isNoDestroy(getASTContext()))
15622 return;
15623
15624 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15625
15626 // If this is an array, we'll require the destructor during initialization, so
15627 // we can skip over this. We still want to emit exit-time destructor warnings
15628 // though.
15629 if (!VD->getType()->isArrayType()) {
15630 MarkFunctionReferenced(VD->getLocation(), Destructor);
15631 CheckDestructorAccess(VD->getLocation(), Destructor,
15632 PDiag(diag::err_access_dtor_var)
15633 << VD->getDeclName() << VD->getType());
15634 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15635 }
15636
15637 if (Destructor->isTrivial()) return;
15638
15639 // If the destructor is constexpr, check whether the variable has constant
15640 // destruction now.
15641 if (Destructor->isConstexpr()) {
15642 bool HasConstantInit = false;
15643 if (VD->getInit() && !VD->getInit()->isValueDependent())
15644 HasConstantInit = VD->evaluateValue();
15646 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15647 HasConstantInit) {
15648 Diag(VD->getLocation(),
15649 diag::err_constexpr_var_requires_const_destruction) << VD;
15650 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15651 Diag(Notes[I].first, Notes[I].second);
15652 }
15653 }
15654
15655 if (!VD->hasGlobalStorage()) return;
15656
15657 // Emit warning for non-trivial dtor in global scope (a real global,
15658 // class-static, function-static).
15659 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15660
15661 // TODO: this should be re-enabled for static locals by !CXAAtExit
15662 if (!VD->isStaticLocal())
15663 Diag(VD->getLocation(), diag::warn_global_destructor);
15664}
15665
15666/// Given a constructor and the set of arguments provided for the
15667/// constructor, convert the arguments and add any required default arguments
15668/// to form a proper call to this constructor.
15669///
15670/// \returns true if an error occurred, false otherwise.
15672 QualType DeclInitType, MultiExprArg ArgsPtr,
15673 SourceLocation Loc,
15674 SmallVectorImpl<Expr *> &ConvertedArgs,
15675 bool AllowExplicit,
15676 bool IsListInitialization) {
15677 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15678 unsigned NumArgs = ArgsPtr.size();
15679 Expr **Args = ArgsPtr.data();
15680
15681 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15682 unsigned NumParams = Proto->getNumParams();
15683
15684 // If too few arguments are available, we'll fill in the rest with defaults.
15685 if (NumArgs < NumParams)
15686 ConvertedArgs.reserve(NumParams);
15687 else
15688 ConvertedArgs.reserve(NumArgs);
15689
15690 VariadicCallType CallType =
15691 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15692 SmallVector<Expr *, 8> AllArgs;
15693 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15694 Proto, 0,
15695 llvm::makeArrayRef(Args, NumArgs),
15696 AllArgs,
15697 CallType, AllowExplicit,
15698 IsListInitialization);
15699 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15700
15701 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15702
15703 CheckConstructorCall(Constructor, DeclInitType,
15704 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15705 Proto, Loc);
15706
15707 return Invalid;
15708}
15709
15710static inline bool
15712 const FunctionDecl *FnDecl) {
15713 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15714 if (isa<NamespaceDecl>(DC)) {
15715 return SemaRef.Diag(FnDecl->getLocation(),
15716 diag::err_operator_new_delete_declared_in_namespace)
15717 << FnDecl->getDeclName();
15718 }
15719
15720 if (isa<TranslationUnitDecl>(DC) &&
15721 FnDecl->getStorageClass() == SC_Static) {
15722 return SemaRef.Diag(FnDecl->getLocation(),
15723 diag::err_operator_new_delete_declared_static)
15724 << FnDecl->getDeclName();
15725 }
15726
15727 return false;
15728}
15729
15731 const PointerType *PtrTy) {
15732 auto &Ctx = SemaRef.Context;
15733 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15734 PtrQuals.removeAddressSpace();
15736 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15737}
15738
15739static inline bool
15741 CanQualType ExpectedResultType,
15742 CanQualType ExpectedFirstParamType,
15743 unsigned DependentParamTypeDiag,
15744 unsigned InvalidParamTypeDiag) {
15745 QualType ResultType =
15746 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15747
15748 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15749 // The operator is valid on any address space for OpenCL.
15750 // Drop address space from actual and expected result types.
15751 if (const auto *PtrTy = ResultType->getAs<PointerType>())
15752 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15753
15754 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15755 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15756 }
15757
15758 // Check that the result type is what we expect.
15759 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15760 // Reject even if the type is dependent; an operator delete function is
15761 // required to have a non-dependent result type.
15762 return SemaRef.Diag(
15763 FnDecl->getLocation(),
15764 ResultType->isDependentType()
15765 ? diag::err_operator_new_delete_dependent_result_type
15766 : diag::err_operator_new_delete_invalid_result_type)
15767 << FnDecl->getDeclName() << ExpectedResultType;
15768 }
15769
15770 // A function template must have at least 2 parameters.
15771 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15772 return SemaRef.Diag(FnDecl->getLocation(),
15773 diag::err_operator_new_delete_template_too_few_parameters)
15774 << FnDecl->getDeclName();
15775
15776 // The function decl must have at least 1 parameter.
15777 if (FnDecl->getNumParams() == 0)
15778 return SemaRef.Diag(FnDecl->getLocation(),
15779 diag::err_operator_new_delete_too_few_parameters)
15780 << FnDecl->getDeclName();
15781
15782 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15783 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15784 // The operator is valid on any address space for OpenCL.
15785 // Drop address space from actual and expected first parameter types.
15786 if (const auto *PtrTy =
15787 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15788 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15789
15790 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15791 ExpectedFirstParamType =
15792 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15793 }
15794
15795 // Check that the first parameter type is what we expect.
15796 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15797 ExpectedFirstParamType) {
15798 // The first parameter type is not allowed to be dependent. As a tentative
15799 // DR resolution, we allow a dependent parameter type if it is the right
15800 // type anyway, to allow destroying operator delete in class templates.
15801 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15802 ? DependentParamTypeDiag
15803 : InvalidParamTypeDiag)
15804 << FnDecl->getDeclName() << ExpectedFirstParamType;
15805 }
15806
15807 return false;
15808}
15809
15810static bool
15812 // C++ [basic.stc.dynamic.allocation]p1:
15813 // A program is ill-formed if an allocation function is declared in a
15814 // namespace scope other than global scope or declared static in global
15815 // scope.
15816 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15817 return true;
15818
15819 CanQualType SizeTy =
15820 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15821
15822 // C++ [basic.stc.dynamic.allocation]p1:
15823 // The return type shall be void*. The first parameter shall have type
15824 // std::size_t.
15825 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15826 SizeTy,
15827 diag::err_operator_new_dependent_param_type,
15828 diag::err_operator_new_param_type))
15829 return true;
15830
15831 // C++ [basic.stc.dynamic.allocation]p1:
15832 // The first parameter shall not have an associated default argument.
15833 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15834 return SemaRef.Diag(FnDecl->getLocation(),
15835 diag::err_operator_new_default_arg)
15836 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15837
15838 return false;
15839}
15840
15841static bool
15843 // C++ [basic.stc.dynamic.deallocation]p1:
15844 // A program is ill-formed if deallocation functions are declared in a
15845 // namespace scope other than global scope or declared static in global
15846 // scope.
15847 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15848 return true;
15849
15850 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15851
15852 // C++ P0722:
15853 // Within a class C, the first parameter of a destroying operator delete
15854 // shall be of type C *. The first parameter of any other deallocation
15855 // function shall be of type void *.
15856 CanQualType ExpectedFirstParamType =
15857 MD && MD->isDestroyingOperatorDelete()
15859 SemaRef.Context.getRecordType(MD->getParent())))
15860 : SemaRef.Context.VoidPtrTy;
15861
15862 // C++ [basic.stc.dynamic.deallocation]p2:
15863 // Each deallocation function shall return void
15865 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15866 diag::err_operator_delete_dependent_param_type,
15867 diag::err_operator_delete_param_type))
15868 return true;
15869
15870 // C++ P0722:
15871 // A destroying operator delete shall be a usual deallocation function.
15872 if (MD && !MD->getParent()->isDependentContext() &&
15874 !SemaRef.isUsualDeallocationFunction(MD)) {
15875 SemaRef.Diag(MD->getLocation(),
15876 diag::err_destroying_operator_delete_not_usual);
15877 return true;
15878 }
15879
15880 return false;
15881}
15882
15883/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15884/// of this overloaded operator is well-formed. If so, returns false;
15885/// otherwise, emits appropriate diagnostics and returns true.
15887 assert(FnDecl && FnDecl->isOverloadedOperator() &&
15888 "Expected an overloaded operator declaration");
15889
15891
15892 // C++ [over.oper]p5:
15893 // The allocation and deallocation functions, operator new,
15894 // operator new[], operator delete and operator delete[], are
15895 // described completely in 3.7.3. The attributes and restrictions
15896 // found in the rest of this subclause do not apply to them unless
15897 // explicitly stated in 3.7.3.
15898 if (Op == OO_Delete || Op == OO_Array_Delete)
15899 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15900
15901 if (Op == OO_New || Op == OO_Array_New)
15902 return CheckOperatorNewDeclaration(*this, FnDecl);
15903
15904 // C++ [over.oper]p6:
15905 // An operator function shall either be a non-static member
15906 // function or be a non-member function and have at least one
15907 // parameter whose type is a class, a reference to a class, an
15908 // enumeration, or a reference to an enumeration.
15909 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15910 if (MethodDecl->isStatic())
15911 return Diag(FnDecl->getLocation(),
15912 diag::err_operator_overload_static) << FnDecl->getDeclName();
15913 } else {
15914 bool ClassOrEnumParam = false;
15915 for (auto Param : FnDecl->parameters()) {
15916 QualType ParamType = Param->getType().getNonReferenceType();
15917 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15918 ParamType->isEnumeralType()) {
15919 ClassOrEnumParam = true;
15920 break;
15921 }
15922 }
15923
15924 if (!ClassOrEnumParam)
15925 return Diag(FnDecl->getLocation(),
15926 diag::err_operator_overload_needs_class_or_enum)
15927 << FnDecl->getDeclName();
15928 }
15929
15930 // C++ [over.oper]p8:
15931 // An operator function cannot have default arguments (8.3.6),
15932 // except where explicitly stated below.
15933 //
15934 // Only the function-call operator (C++ [over.call]p1) and the subscript
15935 // operator (CWG2507) allow default arguments.
15936 if (Op != OO_Call) {
15937 ParmVarDecl *FirstDefaultedParam = nullptr;
15938 for (auto Param : FnDecl->parameters()) {
15939 if (Param->hasDefaultArg()) {
15940 FirstDefaultedParam = Param;
15941 break;
15942 }
15943 }
15944 if (FirstDefaultedParam) {
15945 if (Op == OO_Subscript) {
15946 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15947 ? diag::ext_subscript_overload
15948 : diag::error_subscript_overload)
15949 << FnDecl->getDeclName() << 1
15950 << FirstDefaultedParam->getDefaultArgRange();
15951 } else {
15952 return Diag(FirstDefaultedParam->getLocation(),
15953 diag::err_operator_overload_default_arg)
15954 << FnDecl->getDeclName()
15955 << FirstDefaultedParam->getDefaultArgRange();
15956 }
15957 }
15958 }
15959
15960 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15961 { false, false, false }
15962#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15963 , { Unary, Binary, MemberOnly }
15964#include "clang/Basic/OperatorKinds.def"
15965 };
15966
15967 bool CanBeUnaryOperator = OperatorUses[Op][0];
15968 bool CanBeBinaryOperator = OperatorUses[Op][1];
15969 bool MustBeMemberOperator = OperatorUses[Op][2];
15970
15971 // C++ [over.oper]p8:
15972 // [...] Operator functions cannot have more or fewer parameters
15973 // than the number required for the corresponding operator, as
15974 // described in the rest of this subclause.
15975 unsigned NumParams = FnDecl->getNumParams()
15976 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15977 if (Op != OO_Call && Op != OO_Subscript &&
15978 ((NumParams == 1 && !CanBeUnaryOperator) ||
15979 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15980 (NumParams > 2))) {
15981 // We have the wrong number of parameters.
15982 unsigned ErrorKind;
15983 if (CanBeUnaryOperator && CanBeBinaryOperator) {
15984 ErrorKind = 2; // 2 -> unary or binary.
15985 } else if (CanBeUnaryOperator) {
15986 ErrorKind = 0; // 0 -> unary
15987 } else {
15988 assert(CanBeBinaryOperator &&
15989 "All non-call overloaded operators are unary or binary!");
15990 ErrorKind = 1; // 1 -> binary
15991 }
15992 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15993 << FnDecl->getDeclName() << NumParams << ErrorKind;
15994 }
15995
15996 if (Op == OO_Subscript && NumParams != 2) {
15997 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15998 ? diag::ext_subscript_overload
15999 : diag::error_subscript_overload)
16000 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16001 }
16002
16003 // Overloaded operators other than operator() and operator[] cannot be
16004 // variadic.
16005 if (Op != OO_Call &&
16006 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16007 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16008 << FnDecl->getDeclName();
16009 }
16010
16011 // Some operators must be non-static member functions.
16012 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16013 return Diag(FnDecl->getLocation(),
16014 diag::err_operator_overload_must_be_member)
16015 << FnDecl->getDeclName();
16016 }
16017
16018 // C++ [over.inc]p1:
16019 // The user-defined function called operator++ implements the
16020 // prefix and postfix ++ operator. If this function is a member
16021 // function with no parameters, or a non-member function with one
16022 // parameter of class or enumeration type, it defines the prefix
16023 // increment operator ++ for objects of that type. If the function
16024 // is a member function with one parameter (which shall be of type
16025 // int) or a non-member function with two parameters (the second
16026 // of which shall be of type int), it defines the postfix
16027 // increment operator ++ for objects of that type.
16028 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16029 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16030 QualType ParamType = LastParam->getType();
16031
16032 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16033 !ParamType->isDependentType())
16034 return Diag(LastParam->getLocation(),
16035 diag::err_operator_overload_post_incdec_must_be_int)
16036 << LastParam->getType() << (Op == OO_MinusMinus);
16037 }
16038
16039 return false;
16040}
16041
16042static bool
16044 FunctionTemplateDecl *TpDecl) {
16045 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16046
16047 // Must have one or two template parameters.
16048 if (TemplateParams->size() == 1) {
16049 NonTypeTemplateParmDecl *PmDecl =
16050 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16051
16052 // The template parameter must be a char parameter pack.
16053 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16054 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16055 return false;
16056
16057 // C++20 [over.literal]p5:
16058 // A string literal operator template is a literal operator template
16059 // whose template-parameter-list comprises a single non-type
16060 // template-parameter of class type.
16061 //
16062 // As a DR resolution, we also allow placeholders for deduced class
16063 // template specializations.
16064 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16065 !PmDecl->isTemplateParameterPack() &&
16066 (PmDecl->getType()->isRecordType() ||
16068 return false;
16069 } else if (TemplateParams->size() == 2) {
16070 TemplateTypeParmDecl *PmType =
16071 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16072 NonTypeTemplateParmDecl *PmArgs =
16073 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16074
16075 // The second template parameter must be a parameter pack with the
16076 // first template parameter as its type.
16077 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16078 PmArgs->isTemplateParameterPack()) {
16079 const TemplateTypeParmType *TArgs =
16080 PmArgs->getType()->getAs<TemplateTypeParmType>();
16081 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16082 TArgs->getIndex() == PmType->getIndex()) {
16083 if (!SemaRef.inTemplateInstantiation())
16084 SemaRef.Diag(TpDecl->getLocation(),
16085 diag::ext_string_literal_operator_template);
16086 return false;
16087 }
16088 }
16089 }
16090
16091 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16092 diag::err_literal_operator_template)
16093 << TpDecl->getTemplateParameters()->getSourceRange();
16094 return true;
16095}
16096
16097/// CheckLiteralOperatorDeclaration - Check whether the declaration
16098/// of this literal operator function is well-formed. If so, returns
16099/// false; otherwise, emits appropriate diagnostics and returns true.
16101 if (isa<CXXMethodDecl>(FnDecl)) {
16102 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16103 << FnDecl->getDeclName();
16104 return true;
16105 }
16106
16107 if (FnDecl->isExternC()) {
16108 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16109 if (const LinkageSpecDecl *LSD =
16110 FnDecl->getDeclContext()->getExternCContext())
16111 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16112 return true;
16113 }
16114
16115 // This might be the definition of a literal operator template.
16117
16118 // This might be a specialization of a literal operator template.
16119 if (!TpDecl)
16120 TpDecl = FnDecl->getPrimaryTemplate();
16121
16122 // template <char...> type operator "" name() and
16123 // template <class T, T...> type operator "" name() are the only valid
16124 // template signatures, and the only valid signatures with no parameters.
16125 //
16126 // C++20 also allows template <SomeClass T> type operator "" name().
16127 if (TpDecl) {
16128 if (FnDecl->param_size() != 0) {
16129 Diag(FnDecl->getLocation(),
16130 diag::err_literal_operator_template_with_params);
16131 return true;
16132 }
16133
16135 return true;
16136
16137 } else if (FnDecl->param_size() == 1) {
16138 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16139
16140 QualType ParamType = Param->getType().getUnqualifiedType();
16141
16142 // Only unsigned long long int, long double, any character type, and const
16143 // char * are allowed as the only parameters.
16144 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16145 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16146 Context.hasSameType(ParamType, Context.CharTy) ||
16147 Context.hasSameType(ParamType, Context.WideCharTy) ||
16148 Context.hasSameType(ParamType, Context.Char8Ty) ||
16149 Context.hasSameType(ParamType, Context.Char16Ty) ||
16150 Context.hasSameType(ParamType, Context.Char32Ty)) {
16151 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16152 QualType InnerType = Ptr->getPointeeType();
16153
16154 // Pointer parameter must be a const char *.
16155 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16156 Context.CharTy) &&
16157 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16158 Diag(Param->getSourceRange().getBegin(),
16159 diag::err_literal_operator_param)
16160 << ParamType << "'const char *'" << Param->getSourceRange();
16161 return true;
16162 }
16163
16164 } else if (ParamType->isRealFloatingType()) {
16165 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16166 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16167 return true;
16168
16169 } else if (ParamType->isIntegerType()) {
16170 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16171 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16172 return true;
16173
16174 } else {
16175 Diag(Param->getSourceRange().getBegin(),
16176 diag::err_literal_operator_invalid_param)
16177 << ParamType << Param->getSourceRange();
16178 return true;
16179 }
16180
16181 } else if (FnDecl->param_size() == 2) {
16182 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16183
16184 // First, verify that the first parameter is correct.
16185
16186 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16187
16188 // Two parameter function must have a pointer to const as a
16189 // first parameter; let's strip those qualifiers.
16190 const PointerType *PT = FirstParamType->getAs<PointerType>();
16191
16192 if (!PT) {
16193 Diag((*Param)->getSourceRange().getBegin(),
16194 diag::err_literal_operator_param)
16195 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16196 return true;
16197 }
16198
16199 QualType PointeeType = PT->getPointeeType();
16200 // First parameter must be const
16201 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16202 Diag((*Param)->getSourceRange().getBegin(),
16203 diag::err_literal_operator_param)
16204 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16205 return true;
16206 }
16207
16208 QualType InnerType = PointeeType.getUnqualifiedType();
16209 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16210 // const char32_t* are allowed as the first parameter to a two-parameter
16211 // function
16212 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16213 Context.hasSameType(InnerType, Context.WideCharTy) ||
16214 Context.hasSameType(InnerType, Context.Char8Ty) ||
16215 Context.hasSameType(InnerType, Context.Char16Ty) ||
16216 Context.hasSameType(InnerType, Context.Char32Ty))) {
16217 Diag((*Param)->getSourceRange().getBegin(),
16218 diag::err_literal_operator_param)
16219 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16220 return true;
16221 }
16222
16223 // Move on to the second and final parameter.
16224 ++Param;
16225
16226 // The second parameter must be a std::size_t.
16227 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16228 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16229 Diag((*Param)->getSourceRange().getBegin(),
16230 diag::err_literal_operator_param)
16231 << SecondParamType << Context.getSizeType()
16232 << (*Param)->getSourceRange();
16233 return true;
16234 }
16235 } else {
16236 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16237 return true;
16238 }
16239
16240 // Parameters are good.
16241
16242 // A parameter-declaration-clause containing a default argument is not
16243 // equivalent to any of the permitted forms.
16244 for (auto Param : FnDecl->parameters()) {
16245 if (Param->hasDefaultArg()) {
16246 Diag(Param->getDefaultArgRange().getBegin(),
16247 diag::err_literal_operator_default_argument)
16248 << Param->getDefaultArgRange();
16249 break;
16250 }
16251 }
16252
16253 StringRef LiteralName
16255 if (LiteralName[0] != '_' &&
16256 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16257 // C++11 [usrlit.suffix]p1:
16258 // Literal suffix identifiers that do not start with an underscore
16259 // are reserved for future standardization.
16260 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16261 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16262 }
16263
16264 return false;
16265}
16266
16267/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16268/// linkage specification, including the language and (if present)
16269/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16270/// language string literal. LBraceLoc, if valid, provides the location of
16271/// the '{' brace. Otherwise, this linkage specification does not
16272/// have any braces.
16274 Expr *LangStr,
16275 SourceLocation LBraceLoc) {
16276 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16277 if (!Lit->isOrdinary()) {
16278 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16279 << LangStr->getSourceRange();
16280 return nullptr;
16281 }
16282
16283 StringRef Lang = Lit->getString();
16285 if (Lang == "C")
16287 else if (Lang == "C++")
16289 else {
16290 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16291 << LangStr->getSourceRange();
16292 return nullptr;
16293 }
16294
16295 // FIXME: Add all the various semantics of linkage specifications
16296
16297 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16298 LangStr->getExprLoc(), Language,
16299 LBraceLoc.isValid());
16300
16301 /// C++ [module.unit]p7.2.3
16302 /// - Otherwise, if the declaration
16303 /// - ...
16304 /// - ...
16305 /// - appears within a linkage-specification,
16306 /// it is attached to the global module.
16307 ///
16308 /// If the declaration is already in global module fragment, we don't
16309 /// need to attach it again.
16310 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16311 Module *GlobalModule =
16312 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16313 /// According to [module.reach]p3.2,
16314 /// The declaration in global module fragment is reachable if it is not
16315 /// discarded. And the discarded declaration should be deleted. So it
16316 /// doesn't matter mark the declaration in global module fragment as
16317 /// reachable here.
16318 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
16319 D->setLocalOwningModule(GlobalModule);
16320 }
16321
16322 CurContext->addDecl(D);
16323 PushDeclContext(S, D);
16324 return D;
16325}
16326
16327/// ActOnFinishLinkageSpecification - Complete the definition of
16328/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16329/// valid, it's the position of the closing '}' brace in a linkage
16330/// specification that uses braces.
16332 Decl *LinkageSpec,
16333 SourceLocation RBraceLoc) {
16334 if (RBraceLoc.isValid()) {
16335 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16336 LSDecl->setRBraceLoc(RBraceLoc);
16337 }
16338
16339 // If the current module doesn't has Parent, it implies that the
16340 // LinkageSpec isn't in the module created by itself. So we don't
16341 // need to pop it.
16342 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16343 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16344 PopGlobalModuleFragment();
16345
16346 PopDeclContext();
16347 return LinkageSpec;
16348}
16349
16351 const ParsedAttributesView &AttrList,
16352 SourceLocation SemiLoc) {
16353 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16354 // Attribute declarations appertain to empty declaration so we handle
16355 // them here.
16356 ProcessDeclAttributeList(S, ED, AttrList);
16357
16358 CurContext->addDecl(ED);
16359 return ED;
16360}
16361
16362/// Perform semantic analysis for the variable declaration that
16363/// occurs within a C++ catch clause, returning the newly-created
16364/// variable.
16366 TypeSourceInfo *TInfo,
16367 SourceLocation StartLoc,
16368 SourceLocation Loc,
16369 IdentifierInfo *Name) {
16370 bool Invalid = false;
16371 QualType ExDeclType = TInfo->getType();
16372
16373 // Arrays and functions decay.
16374 if (ExDeclType->isArrayType())
16375 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16376 else if (ExDeclType->isFunctionType())
16377 ExDeclType = Context.getPointerType(ExDeclType);
16378
16379 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16380 // The exception-declaration shall not denote a pointer or reference to an
16381 // incomplete type, other than [cv] void*.
16382 // N2844 forbids rvalue references.
16383 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16384 Diag(Loc, diag::err_catch_rvalue_ref);
16385 Invalid = true;
16386 }
16387
16388 if (ExDeclType->isVariablyModifiedType()) {
16389 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16390 Invalid = true;
16391 }
16392
16393 QualType BaseType = ExDeclType;
16394 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16395 unsigned DK = diag::err_catch_incomplete;
16396 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16397 BaseType = Ptr->getPointeeType();
16398 Mode = 1;
16399 DK = diag::err_catch_incomplete_ptr;
16400 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16401 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16402 BaseType = Ref->getPointeeType();
16403 Mode = 2;
16404 DK = diag::err_catch_incomplete_ref;
16405 }
16406 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16407 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16408 Invalid = true;
16409
16410 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16411 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16412 Invalid = true;
16413 }
16414
16415 if (!Invalid && !ExDeclType->isDependentType() &&
16416 RequireNonAbstractType(Loc, ExDeclType,
16417 diag::err_abstract_type_in_decl,
16418 AbstractVariableType))
16419 Invalid = true;
16420
16421 // Only the non-fragile NeXT runtime currently supports C++ catches
16422 // of ObjC types, and no runtime supports catching ObjC types by value.
16423 if (!Invalid && getLangOpts().ObjC) {
16424 QualType T = ExDeclType;
16425 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16426 T = RT->getPointeeType();
16427
16428 if (T->isObjCObjectType()) {
16429 Diag(Loc, diag::err_objc_object_catch);
16430 Invalid = true;
16431 } else if (T->isObjCObjectPointerType()) {
16432 // FIXME: should this be a test for macosx-fragile specifically?
16433 if (getLangOpts().ObjCRuntime.isFragile())
16434 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16435 }
16436 }
16437
16438 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16439 ExDeclType, TInfo, SC_None);
16440 ExDecl->setExceptionVariable(true);
16441
16442 // In ARC, infer 'retaining' for variables of retainable type.
16443 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16444 Invalid = true;
16445
16446 if (!Invalid && !ExDeclType->isDependentType()) {
16447 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16448 // Insulate this from anything else we might currently be parsing.
16450 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16451
16452 // C++ [except.handle]p16:
16453 // The object declared in an exception-declaration or, if the
16454 // exception-declaration does not specify a name, a temporary (12.2) is
16455 // copy-initialized (8.5) from the exception object. [...]
16456 // The object is destroyed when the handler exits, after the destruction
16457 // of any automatic objects initialized within the handler.
16458 //
16459 // We just pretend to initialize the object with itself, then make sure
16460 // it can be destroyed later.
16461 QualType initType = Context.getExceptionObjectType(ExDeclType);
16462
16463 InitializedEntity entity =
16465 InitializationKind initKind =
16467
16468 Expr *opaqueValue =
16469 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16470 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16471 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16472 if (result.isInvalid())
16473 Invalid = true;
16474 else {
16475 // If the constructor used was non-trivial, set this as the
16476 // "initializer".
16477 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16478 if (!construct->getConstructor()->isTrivial()) {
16479 Expr *init = MaybeCreateExprWithCleanups(construct);
16480 ExDecl->setInit(init);
16481 }
16482
16483 // And make sure it's destructable.
16484 FinalizeVarWithDestructor(ExDecl, recordType);
16485 }
16486 }
16487 }
16488
16489 if (Invalid)
16490 ExDecl->setInvalidDecl();
16491
16492 return ExDecl;
16493}
16494
16495/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16496/// handler.
16498 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16499 bool Invalid = D.isInvalidType();
16500
16501 // Check for unexpanded parameter packs.
16502 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16503 UPPC_ExceptionType)) {
16504 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16505 D.getIdentifierLoc());
16506 Invalid = true;
16507 }
16508
16509 IdentifierInfo *II = D.getIdentifier();
16510 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16511 LookupOrdinaryName,
16512 ForVisibleRedeclaration)) {
16513 // The scope should be freshly made just for us. There is just no way
16514 // it contains any previous declaration, except for function parameters in
16515 // a function-try-block's catch statement.
16516 assert(!S->isDeclScope(PrevDecl));
16517 if (isDeclInScope(PrevDecl, CurContext, S)) {
16518 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16519 << D.getIdentifier();
16520 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16521 Invalid = true;
16522 } else if (PrevDecl->isTemplateParameter())
16523 // Maybe we will complain about the shadowed template parameter.
16524 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16525 }
16526
16527 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16528 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16529 << D.getCXXScopeSpec().getRange();
16530 Invalid = true;
16531 }
16532
16533 VarDecl *ExDecl = BuildExceptionDeclaration(
16534 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16535 if (Invalid)
16536 ExDecl->setInvalidDecl();
16537
16538 // Add the exception declaration into this scope.
16539 if (II)
16540 PushOnScopeChains(ExDecl, S);
16541 else
16542 CurContext->addDecl(ExDecl);
16543
16544 ProcessDeclAttributes(S, ExDecl, D);
16545 return ExDecl;
16546}
16547
16549 Expr *AssertExpr,
16550 Expr *AssertMessageExpr,
16551 SourceLocation RParenLoc) {
16552 StringLiteral *AssertMessage =
16553 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16554
16555 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16556 return nullptr;
16557
16558 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16559 AssertMessage, RParenLoc, false);
16560}
16561
16563 Expr *AssertExpr,
16564 StringLiteral *AssertMessage,
16565 SourceLocation RParenLoc,
16566 bool Failed) {
16567 assert(AssertExpr != nullptr && "Expected non-null condition");
16568 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16569 !Failed) {
16570 // In a static_assert-declaration, the constant-expression shall be a
16571 // constant expression that can be contextually converted to bool.
16572 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16573 if (Converted.isInvalid())
16574 Failed = true;
16575
16576 ExprResult FullAssertExpr =
16577 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16578 /*DiscardedValue*/ false,
16579 /*IsConstexpr*/ true);
16580 if (FullAssertExpr.isInvalid())
16581 Failed = true;
16582 else
16583 AssertExpr = FullAssertExpr.get();
16584
16585 llvm::APSInt Cond;
16586 if (!Failed && VerifyIntegerConstantExpression(
16587 AssertExpr, &Cond,
16588 diag::err_static_assert_expression_is_not_constant)
16589 .isInvalid())
16590 Failed = true;
16591
16592 if (!Failed && !Cond) {
16593 SmallString<256> MsgBuffer;
16594 llvm::raw_svector_ostream Msg(MsgBuffer);
16595 if (AssertMessage) {
16596 const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16597 if (MsgStr->isOrdinary())
16598 Msg << MsgStr->getString();
16599 else
16600 MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
16601 }
16602
16603 Expr *InnerCond = nullptr;
16604 std::string InnerCondDescription;
16605 std::tie(InnerCond, InnerCondDescription) =
16606 findFailedBooleanCondition(Converted.get());
16607 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16608 // Drill down into concept specialization expressions to see why they
16609 // weren't satisfied.
16610 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16611 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16612 ConstraintSatisfaction Satisfaction;
16613 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16614 DiagnoseUnsatisfiedConstraint(Satisfaction);
16615 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16616 && !isa<IntegerLiteral>(InnerCond)) {
16617 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16618 << InnerCondDescription << !AssertMessage
16619 << Msg.str() << InnerCond->getSourceRange();
16620 } else {
16621 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16622 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16623 }
16624 Failed = true;
16625 }
16626 } else {
16627 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16628 /*DiscardedValue*/false,
16629 /*IsConstexpr*/true);
16630 if (FullAssertExpr.isInvalid())
16631 Failed = true;
16632 else
16633 AssertExpr = FullAssertExpr.get();
16634 }
16635
16636 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16637 AssertExpr, AssertMessage, RParenLoc,
16638 Failed);
16639
16640 CurContext->addDecl(Decl);
16641 return Decl;
16642}
16643
16644/// Perform semantic analysis of the given friend type declaration.
16645///
16646/// \returns A friend declaration that.
16648 SourceLocation FriendLoc,
16649 TypeSourceInfo *TSInfo) {
16650 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16651
16652 QualType T = TSInfo->getType();
16653 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16654
16655 // C++03 [class.friend]p2:
16656 // An elaborated-type-specifier shall be used in a friend declaration
16657 // for a class.*
16658 //
16659 // * The class-key of the elaborated-type-specifier is required.
16660 if (!CodeSynthesisContexts.empty()) {
16661 // Do not complain about the form of friend template types during any kind
16662 // of code synthesis. For template instantiation, we will have complained
16663 // when the template was defined.
16664 } else {
16665 if (!T->isElaboratedTypeSpecifier()) {
16666 // If we evaluated the type to a record type, suggest putting
16667 // a tag in front.
16668 if (const RecordType *RT = T->getAs<RecordType>()) {
16669 RecordDecl *RD = RT->getDecl();
16670
16671 SmallString<16> InsertionText(" ");
16672 InsertionText += RD->getKindName();
16673
16674 Diag(TypeRange.getBegin(),
16675 getLangOpts().CPlusPlus11 ?
16676 diag::warn_cxx98_compat_unelaborated_friend_type :
16677 diag::ext_unelaborated_friend_type)
16678 << (unsigned) RD->getTagKind()
16679 << T
16680 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16681 InsertionText);
16682 } else {
16683 Diag(FriendLoc,
16684 getLangOpts().CPlusPlus11 ?
16685 diag::warn_cxx98_compat_nonclass_type_friend :
16686 diag::ext_nonclass_type_friend)
16687 << T
16688 << TypeRange;
16689 }
16690 } else if (T->getAs<EnumType>()) {
16691 Diag(FriendLoc,
16692 getLangOpts().CPlusPlus11 ?
16693 diag::warn_cxx98_compat_enum_friend :
16694 diag::ext_enum_friend)
16695 << T
16696 << TypeRange;
16697 }
16698
16699 // C++11 [class.friend]p3:
16700 // A friend declaration that does not declare a function shall have one
16701 // of the following forms:
16702 // friend elaborated-type-specifier ;
16703 // friend simple-type-specifier ;
16704 // friend typename-specifier ;
16705 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16706 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16707 }
16708
16709 // If the type specifier in a friend declaration designates a (possibly
16710 // cv-qualified) class type, that class is declared as a friend; otherwise,
16711 // the friend declaration is ignored.
16712 return FriendDecl::Create(Context, CurContext,
16713 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16714 FriendLoc);
16715}
16716
16717/// Handle a friend tag declaration where the scope specifier was
16718/// templated.
16720 unsigned TagSpec, SourceLocation TagLoc,
16721 CXXScopeSpec &SS, IdentifierInfo *Name,
16722 SourceLocation NameLoc,
16724 MultiTemplateParamsArg TempParamLists) {
16726
16727 bool IsMemberSpecialization = false;
16728 bool Invalid = false;
16729
16730 if (TemplateParameterList *TemplateParams =
16731 MatchTemplateParametersToScopeSpecifier(
16732 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16733 IsMemberSpecialization, Invalid)) {
16734 if (TemplateParams->size() > 0) {
16735 // This is a declaration of a class template.
16736 if (Invalid)
16737 return nullptr;
16738
16739 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16740 NameLoc, Attr, TemplateParams, AS_public,
16741 /*ModulePrivateLoc=*/SourceLocation(),
16742 FriendLoc, TempParamLists.size() - 1,
16743 TempParamLists.data()).get();
16744 } else {
16745 // The "template<>" header is extraneous.
16746 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16747 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16748 IsMemberSpecialization = true;
16749 }
16750 }
16751
16752 if (Invalid) return nullptr;
16753
16754 bool isAllExplicitSpecializations = true;
16755 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16756 if (TempParamLists[I]->size()) {
16757 isAllExplicitSpecializations = false;
16758 break;
16759 }
16760 }
16761
16762 // FIXME: don't ignore attributes.
16763
16764 // If it's explicit specializations all the way down, just forget
16765 // about the template header and build an appropriate non-templated
16766 // friend. TODO: for source fidelity, remember the headers.
16767 if (isAllExplicitSpecializations) {
16768 if (SS.isEmpty()) {
16769 bool Owned = false;
16770 bool IsDependent = false;
16771 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16772 Attr, AS_public,
16773 /*ModulePrivateLoc=*/SourceLocation(),
16774 MultiTemplateParamsArg(), Owned, IsDependent,
16775 /*ScopedEnumKWLoc=*/SourceLocation(),
16776 /*ScopedEnumUsesClassTag=*/false,
16777 /*UnderlyingType=*/TypeResult(),
16778 /*IsTypeSpecifier=*/false,
16779 /*IsTemplateParamOrArg=*/false);
16780 }
16781
16782 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16783 ElaboratedTypeKeyword Keyword
16785 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16786 *Name, NameLoc);
16787 if (T.isNull())
16788 return nullptr;
16789
16790 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16791 if (isa<DependentNameType>(T)) {
16794 TL.setElaboratedKeywordLoc(TagLoc);
16795 TL.setQualifierLoc(QualifierLoc);
16796 TL.setNameLoc(NameLoc);
16797 } else {
16799 TL.setElaboratedKeywordLoc(TagLoc);
16800 TL.setQualifierLoc(QualifierLoc);
16801 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16802 }
16803
16804 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16805 TSI, FriendLoc, TempParamLists);
16806 Friend->setAccess(AS_public);
16807 CurContext->addDecl(Friend);
16808 return Friend;
16809 }
16810
16811 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16812
16813
16814
16815 // Handle the case of a templated-scope friend class. e.g.
16816 // template <class T> class A<T>::B;
16817 // FIXME: we don't support these right now.
16818 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16819 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16821 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16822 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16824 TL.setElaboratedKeywordLoc(TagLoc);
16825 TL.setQualifierLoc(SS.getWithLocInContext(Context));
16826 TL.setNameLoc(NameLoc);
16827
16828 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16829 TSI, FriendLoc, TempParamLists);
16830 Friend->setAccess(AS_public);
16831 Friend->setUnsupportedFriend(true);
16832 CurContext->addDecl(Friend);
16833 return Friend;
16834}
16835
16836/// Handle a friend type declaration. This works in tandem with
16837/// ActOnTag.
16838///
16839/// Notes on friend class templates:
16840///
16841/// We generally treat friend class declarations as if they were
16842/// declaring a class. So, for example, the elaborated type specifier
16843/// in a friend declaration is required to obey the restrictions of a
16844/// class-head (i.e. no typedefs in the scope chain), template
16845/// parameters are required to match up with simple template-ids, &c.
16846/// However, unlike when declaring a template specialization, it's
16847/// okay to refer to a template specialization without an empty
16848/// template parameter declaration, e.g.
16849/// friend class A<T>::B<unsigned>;
16850/// We permit this as a special case; if there are any template
16851/// parameters present at all, require proper matching, i.e.
16852/// template <> template <class T> friend class A<int>::B;
16854 MultiTemplateParamsArg TempParams) {
16855 SourceLocation Loc = DS.getBeginLoc();
16856
16857 assert(DS.isFriendSpecified());
16859
16860 // C++ [class.friend]p3:
16861 // A friend declaration that does not declare a function shall have one of
16862 // the following forms:
16863 // friend elaborated-type-specifier ;
16864 // friend simple-type-specifier ;
16865 // friend typename-specifier ;
16866 //
16867 // Any declaration with a type qualifier does not have that form. (It's
16868 // legal to specify a qualified type as a friend, you just can't write the
16869 // keywords.)
16870 if (DS.getTypeQualifiers()) {
16872 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16874 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16876 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16878 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16880 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16881 }
16882
16883 // Try to convert the decl specifier to a type. This works for
16884 // friend templates because ActOnTag never produces a ClassTemplateDecl
16885 // for a TUK_Friend.
16886 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
16887 DeclaratorContext::Member);
16888 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16889 QualType T = TSI->getType();
16890 if (TheDeclarator.isInvalidType())
16891 return nullptr;
16892
16893 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16894 return nullptr;
16895
16896 // This is definitely an error in C++98. It's probably meant to
16897 // be forbidden in C++0x, too, but the specification is just
16898 // poorly written.
16899 //
16900 // The problem is with declarations like the following:
16901 // template <T> friend A<T>::foo;
16902 // where deciding whether a class C is a friend or not now hinges
16903 // on whether there exists an instantiation of A that causes
16904 // 'foo' to equal C. There are restrictions on class-heads
16905 // (which we declare (by fiat) elaborated friend declarations to
16906 // be) that makes this tractable.
16907 //
16908 // FIXME: handle "template <> friend class A<T>;", which
16909 // is possibly well-formed? Who even knows?
16910 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16911 Diag(Loc, diag::err_tagless_friend_type_template)
16912 << DS.getSourceRange();
16913 return nullptr;
16914 }
16915
16916 // C++98 [class.friend]p1: A friend of a class is a function
16917 // or class that is not a member of the class . . .
16918 // This is fixed in DR77, which just barely didn't make the C++03
16919 // deadline. It's also a very silly restriction that seriously
16920 // affects inner classes and which nobody else seems to implement;
16921 // thus we never diagnose it, not even in -pedantic.
16922 //
16923 // But note that we could warn about it: it's always useless to
16924 // friend one of your own members (it's not, however, worthless to
16925 // friend a member of an arbitrary specialization of your template).
16926
16927 Decl *D;
16928 if (!TempParams.empty())
16929 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16930 TempParams,
16931 TSI,
16932 DS.getFriendSpecLoc());
16933 else
16934 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16935
16936 if (!D)
16937 return nullptr;
16938
16939 D->setAccess(AS_public);
16940 CurContext->addDecl(D);
16941
16942 return D;
16943}
16944
16946 MultiTemplateParamsArg TemplateParams) {
16947 const DeclSpec &DS = D.getDeclSpec();
16948
16949 assert(DS.isFriendSpecified());
16951
16953 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16954
16955 // C++ [class.friend]p1
16956 // A friend of a class is a function or class....
16957 // Note that this sees through typedefs, which is intended.
16958 // It *doesn't* see through dependent types, which is correct
16959 // according to [temp.arg.type]p3:
16960 // If a declaration acquires a function type through a
16961 // type dependent on a template-parameter and this causes
16962 // a declaration that does not use the syntactic form of a
16963 // function declarator to have a function type, the program
16964 // is ill-formed.
16965 if (!TInfo->getType()->isFunctionType()) {
16966 Diag(Loc, diag::err_unexpected_friend);
16967
16968 // It might be worthwhile to try to recover by creating an
16969 // appropriate declaration.
16970 return nullptr;
16971 }
16972
16973 // C++ [namespace.memdef]p3
16974 // - If a friend declaration in a non-local class first declares a
16975 // class or function, the friend class or function is a member
16976 // of the innermost enclosing namespace.
16977 // - The name of the friend is not found by simple name lookup
16978 // until a matching declaration is provided in that namespace
16979 // scope (either before or after the class declaration granting
16980 // friendship).
16981 // - If a friend function is called, its name may be found by the
16982 // name lookup that considers functions from namespaces and
16983 // classes associated with the types of the function arguments.
16984 // - When looking for a prior declaration of a class or a function
16985 // declared as a friend, scopes outside the innermost enclosing
16986 // namespace scope are not considered.
16987
16988 CXXScopeSpec &SS = D.getCXXScopeSpec();
16989 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16990 assert(NameInfo.getName());
16991
16992 // Check for unexpanded parameter packs.
16993 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16994 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16995 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16996 return nullptr;
16997
16998 // The context we found the declaration in, or in which we should
16999 // create the declaration.
17000 DeclContext *DC;
17001 Scope *DCScope = S;
17002 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17003 ForExternalRedeclaration);
17004
17005 // There are five cases here.
17006 // - There's no scope specifier and we're in a local class. Only look
17007 // for functions declared in the immediately-enclosing block scope.
17008 // We recover from invalid scope qualifiers as if they just weren't there.
17009 FunctionDecl *FunctionContainingLocalClass = nullptr;
17010 if ((SS.isInvalid() || !SS.isSet()) &&
17011 (FunctionContainingLocalClass =
17012 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17013 // C++11 [class.friend]p11:
17014 // If a friend declaration appears in a local class and the name
17015 // specified is an unqualified name, a prior declaration is
17016 // looked up without considering scopes that are outside the
17017 // innermost enclosing non-class scope. For a friend function
17018 // declaration, if there is no prior declaration, the program is
17019 // ill-formed.
17020
17021 // Find the innermost enclosing non-class scope. This is the block
17022 // scope containing the local class definition (or for a nested class,
17023 // the outer local class).
17024 DCScope = S->getFnParent();
17025
17026 // Look up the function name in the scope.
17027 Previous.clear(LookupLocalFriendName);
17028 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17029
17030 if (!Previous.empty()) {
17031 // All possible previous declarations must have the same context:
17032 // either they were declared at block scope or they are members of
17033 // one of the enclosing local classes.
17034 DC = Previous.getRepresentativeDecl()->getDeclContext();
17035 } else {
17036 // This is ill-formed, but provide the context that we would have
17037 // declared the function in, if we were permitted to, for error recovery.
17038 DC = FunctionContainingLocalClass;
17039 }
17040 adjustContextForLocalExternDecl(DC);
17041
17042 // C++ [class.friend]p6:
17043 // A function can be defined in a friend declaration of a class if and
17044 // only if the class is a non-local class (9.8), the function name is
17045 // unqualified, and the function has namespace scope.
17046 if (D.isFunctionDefinition()) {
17047 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17048 }
17049
17050 // - There's no scope specifier, in which case we just go to the
17051 // appropriate scope and look for a function or function template
17052 // there as appropriate.
17053 } else if (SS.isInvalid() || !SS.isSet()) {
17054 // C++11 [namespace.memdef]p3:
17055 // If the name in a friend declaration is neither qualified nor
17056 // a template-id and the declaration is a function or an
17057 // elaborated-type-specifier, the lookup to determine whether
17058 // the entity has been previously declared shall not consider
17059 // any scopes outside the innermost enclosing namespace.
17060 bool isTemplateId =
17061 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17062
17063 // Find the appropriate context according to the above.
17064 DC = CurContext;
17065
17066 // Skip class contexts. If someone can cite chapter and verse
17067 // for this behavior, that would be nice --- it's what GCC and
17068 // EDG do, and it seems like a reasonable intent, but the spec
17069 // really only says that checks for unqualified existing
17070 // declarations should stop at the nearest enclosing namespace,
17071 // not that they should only consider the nearest enclosing
17072 // namespace.
17073 while (DC->isRecord())
17074 DC = DC->getParent();
17075
17076 DeclContext *LookupDC = DC->getNonTransparentContext();
17077 while (true) {
17078 LookupQualifiedName(Previous, LookupDC);
17079
17080 if (!Previous.empty()) {
17081 DC = LookupDC;
17082 break;
17083 }
17084
17085 if (isTemplateId) {
17086 if (isa<TranslationUnitDecl>(LookupDC)) break;
17087 } else {
17088 if (LookupDC->isFileContext()) break;
17089 }
17090 LookupDC = LookupDC->getParent();
17091 }
17092
17093 DCScope = getScopeForDeclContext(S, DC);
17094
17095 // - There's a non-dependent scope specifier, in which case we
17096 // compute it and do a previous lookup there for a function
17097 // or function template.
17098 } else if (!SS.getScopeRep()->isDependent()) {
17099 DC = computeDeclContext(SS);
17100 if (!DC) return nullptr;
17101
17102 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17103
17104 LookupQualifiedName(Previous, DC);
17105
17106 // C++ [class.friend]p1: A friend of a class is a function or
17107 // class that is not a member of the class . . .
17108 if (DC->Equals(CurContext))
17110 getLangOpts().CPlusPlus11 ?
17111 diag::warn_cxx98_compat_friend_is_member :
17112 diag::err_friend_is_member);
17113
17114 if (D.isFunctionDefinition()) {
17115 // C++ [class.friend]p6:
17116 // A function can be defined in a friend declaration of a class if and
17117 // only if the class is a non-local class (9.8), the function name is
17118 // unqualified, and the function has namespace scope.
17119 //
17120 // FIXME: We should only do this if the scope specifier names the
17121 // innermost enclosing namespace; otherwise the fixit changes the
17122 // meaning of the code.
17124 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17125
17126 DB << SS.getScopeRep();
17127 if (DC->isFileContext())
17129 SS.clear();
17130 }
17131
17132 // - There's a scope specifier that does not match any template
17133 // parameter lists, in which case we use some arbitrary context,
17134 // create a method or method template, and wait for instantiation.
17135 // - There's a scope specifier that does match some template
17136 // parameter lists, which we don't handle right now.
17137 } else {
17138 if (D.isFunctionDefinition()) {
17139 // C++ [class.friend]p6:
17140 // A function can be defined in a friend declaration of a class if and
17141 // only if the class is a non-local class (9.8), the function name is
17142 // unqualified, and the function has namespace scope.
17143 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17144 << SS.getScopeRep();
17145 }
17146
17147 DC = CurContext;
17148 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17149 }
17150
17151 if (!DC->isRecord()) {
17152 int DiagArg = -1;
17153 switch (D.getName().getKind()) {
17154 case UnqualifiedIdKind::IK_ConstructorTemplateId:
17155 case UnqualifiedIdKind::IK_ConstructorName:
17156 DiagArg = 0;
17157 break;
17158 case UnqualifiedIdKind::IK_DestructorName:
17159 DiagArg = 1;
17160 break;
17161 case UnqualifiedIdKind::IK_ConversionFunctionId:
17162 DiagArg = 2;
17163 break;
17164 case UnqualifiedIdKind::IK_DeductionGuideName:
17165 DiagArg = 3;
17166 break;
17167 case UnqualifiedIdKind::IK_Identifier:
17168 case UnqualifiedIdKind::IK_ImplicitSelfParam:
17169 case UnqualifiedIdKind::IK_LiteralOperatorId:
17170 case UnqualifiedIdKind::IK_OperatorFunctionId:
17171 case UnqualifiedIdKind::IK_TemplateId:
17172 break;
17173 }
17174 // This implies that it has to be an operator or function.
17175 if (DiagArg >= 0) {
17176 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17177 return nullptr;
17178 }
17179 }
17180
17181 // FIXME: This is an egregious hack to cope with cases where the scope stack
17182 // does not contain the declaration context, i.e., in an out-of-line
17183 // definition of a class.
17184 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17185 if (!DCScope) {
17186 FakeDCScope.setEntity(DC);
17187 DCScope = &FakeDCScope;
17188 }
17189
17190 bool AddToScope = true;
17191 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17192 TemplateParams, AddToScope);
17193 if (!ND) return nullptr;
17194
17195 assert(ND->getLexicalDeclContext() == CurContext);
17196
17197 // If we performed typo correction, we might have added a scope specifier
17198 // and changed the decl context.
17199 DC = ND->getDeclContext();
17200
17201 // Add the function declaration to the appropriate lookup tables,
17202 // adjusting the redeclarations list as necessary. We don't
17203 // want to do this yet if the friending class is dependent.
17204 //
17205 // Also update the scope-based lookup if the target context's
17206 // lookup context is in lexical scope.
17207 if (!CurContext->isDependentContext()) {
17208 DC = DC->getRedeclContext();
17210 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17211 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17212 }
17213
17214 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17215 D.getIdentifierLoc(), ND,
17216 DS.getFriendSpecLoc());
17217 FrD->setAccess(AS_public);
17218 CurContext->addDecl(FrD);
17219
17220 if (ND->isInvalidDecl()) {
17221 FrD->setInvalidDecl();
17222 } else {
17223 if (DC->isRecord()) CheckFriendAccess(ND);
17224
17225 FunctionDecl *FD;
17226 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17227 FD = FTD->getTemplatedDecl();
17228 else
17229 FD = cast<FunctionDecl>(ND);
17230
17231 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17232 // default argument expression, that declaration shall be a definition
17233 // and shall be the only declaration of the function or function
17234 // template in the translation unit.
17236 // We can't look at FD->getPreviousDecl() because it may not have been set
17237 // if we're in a dependent context. If the function is known to be a
17238 // redeclaration, we will have narrowed Previous down to the right decl.
17239 if (D.isRedeclaration()) {
17240 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17241 Diag(Previous.getRepresentativeDecl()->getLocation(),
17242 diag::note_previous_declaration);
17243 } else if (!D.isFunctionDefinition())
17244 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17245 }
17246
17247 // Mark templated-scope function declarations as unsupported.
17248 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17249 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17250 << SS.getScopeRep() << SS.getRange()
17251 << cast<CXXRecordDecl>(CurContext);
17252 FrD->setUnsupportedFriend(true);
17253 }
17254 }
17255
17256 warnOnReservedIdentifier(ND);
17257
17258 return ND;
17259}
17260
17262 AdjustDeclIfTemplate(Dcl);
17263
17264 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17265 if (!Fn) {
17266 Diag(DelLoc, diag::err_deleted_non_function);
17267 return;
17268 }
17269
17270 // Deleted function does not have a body.
17271 Fn->setWillHaveBody(false);
17272
17273 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17274 // Don't consider the implicit declaration we generate for explicit
17275 // specializations. FIXME: Do not generate these implicit declarations.
17276 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17277 Prev->getPreviousDecl()) &&
17278 !Prev->isDefined()) {
17279 Diag(DelLoc, diag::err_deleted_decl_not_first);
17280 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17281 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17282 : diag::note_previous_declaration);
17283 // We can't recover from this; the declaration might have already
17284 // been used.
17285 Fn->setInvalidDecl();
17286 return;
17287 }
17288
17289 // To maintain the invariant that functions are only deleted on their first
17290 // declaration, mark the implicitly-instantiated declaration of the
17291 // explicitly-specialized function as deleted instead of marking the
17292 // instantiated redeclaration.
17293 Fn = Fn->getCanonicalDecl();
17294 }
17295
17296 // dllimport/dllexport cannot be deleted.
17297 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17298 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17299 Fn->setInvalidDecl();
17300 }
17301
17302 // C++11 [basic.start.main]p3:
17303 // A program that defines main as deleted [...] is ill-formed.
17304 if (Fn->isMain())
17305 Diag(DelLoc, diag::err_deleted_main);
17306
17307 // C++11 [dcl.fct.def.delete]p4:
17308 // A deleted function is implicitly inline.
17309 Fn->setImplicitlyInline();
17310 Fn->setDeletedAsWritten();
17311}
17312
17314 if (!Dcl || Dcl->isInvalidDecl())
17315 return;
17316
17317 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17318 if (!FD) {
17319 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17320 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17321 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17322 return;
17323 }
17324 }
17325
17326 Diag(DefaultLoc, diag::err_default_special_members)
17327 << getLangOpts().CPlusPlus20;
17328 return;
17329 }
17330
17331 // Reject if this can't possibly be a defaultable function.
17332 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17333 if (!DefKind &&
17334 // A dependent function that doesn't locally look defaultable can
17335 // still instantiate to a defaultable function if it's a constructor
17336 // or assignment operator.
17337 (!FD->isDependentContext() ||
17338 (!isa<CXXConstructorDecl>(FD) &&
17339 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17340 Diag(DefaultLoc, diag::err_default_special_members)
17341 << getLangOpts().CPlusPlus20;
17342 return;
17343 }
17344
17345 // Issue compatibility warning. We already warned if the operator is
17346 // 'operator<=>' when parsing the '<=>' token.
17347 if (DefKind.isComparison() &&
17348 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17349 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17350 ? diag::warn_cxx17_compat_defaulted_comparison
17351 : diag::ext_defaulted_comparison);
17352 }
17353
17354 FD->setDefaulted();
17355 FD->setExplicitlyDefaulted();
17356
17357 // Defer checking functions that are defaulted in a dependent context.
17358 if (FD->isDependentContext())
17359 return;
17360
17361 // Unset that we will have a body for this function. We might not,
17362 // if it turns out to be trivial, and we don't need this marking now
17363 // that we've marked it as defaulted.
17364 FD->setWillHaveBody(false);
17365
17366 if (DefKind.isComparison()) {
17367 // If this comparison's defaulting occurs within the definition of its
17368 // lexical class context, we have to do the checking when complete.
17369 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17370 if (!RD->isCompleteDefinition())
17371 return;
17372 }
17373
17374 // If this member fn was defaulted on its first declaration, we will have
17375 // already performed the checking in CheckCompletedCXXClass. Such a
17376 // declaration doesn't trigger an implicit definition.
17377 if (isa<CXXMethodDecl>(FD)) {
17378 const FunctionDecl *Primary = FD;
17379 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17380 // Ask the template instantiation pattern that actually had the
17381 // '= default' on it.
17382 Primary = Pattern;
17383 if (Primary->getCanonicalDecl()->isDefaulted())
17384 return;
17385 }
17386
17387 if (DefKind.isComparison()) {
17388 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17389 FD->setInvalidDecl();
17390 else
17391 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17392 } else {
17393 auto *MD = cast<CXXMethodDecl>(FD);
17394
17395 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17396 MD->setInvalidDecl();
17397 else
17398 DefineDefaultedFunction(*this, MD, DefaultLoc);
17399 }
17400}
17401
17402static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17403 for (Stmt *SubStmt : S->children()) {
17404 if (!SubStmt)
17405 continue;
17406 if (isa<ReturnStmt>(SubStmt))
17407 Self.Diag(SubStmt->getBeginLoc(),
17408 diag::err_return_in_constructor_handler);
17409 if (!isa<Expr>(SubStmt))
17410 SearchForReturnInStmt(Self, SubStmt);
17411 }
17412}
17413
17415 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17416 CXXCatchStmt *Handler = TryBlock->getHandler(I);
17417 SearchForReturnInStmt(*this, Handler);
17418 }
17419}
17420
17422 FnBodyKind BodyKind) {
17423 switch (BodyKind) {
17424 case FnBodyKind::Delete:
17425 SetDeclDeleted(D, Loc);
17426 break;
17427 case FnBodyKind::Default:
17428 SetDeclDefaulted(D, Loc);
17429 break;
17430 case FnBodyKind::Other:
17431 llvm_unreachable(
17432 "Parsed function body should be '= delete;' or '= default;'");
17433 }
17434}
17435
17437 const CXXMethodDecl *Old) {
17438 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17439 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17440
17441 if (OldFT->hasExtParameterInfos()) {
17442 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17443 // A parameter of the overriding method should be annotated with noescape
17444 // if the corresponding parameter of the overridden method is annotated.
17445 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17446 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17447 Diag(New->getParamDecl(I)->getLocation(),
17448 diag::warn_overriding_method_missing_noescape);
17449 Diag(Old->getParamDecl(I)->getLocation(),
17450 diag::note_overridden_marked_noescape);
17451 }
17452 }
17453
17454 // Virtual overrides must have the same code_seg.
17455 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17456 const auto *NewCSA = New->getAttr<CodeSegAttr>();
17457 if ((NewCSA || OldCSA) &&
17458 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17459 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17460 Diag(Old->getLocation(), diag::note_previous_declaration);
17461 return true;
17462 }
17463
17464 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17465
17466 // If the calling conventions match, everything is fine
17467 if (NewCC == OldCC)
17468 return false;
17469
17470 // If the calling conventions mismatch because the new function is static,
17471 // suppress the calling convention mismatch error; the error about static
17472 // function override (err_static_overrides_virtual from
17473 // Sema::CheckFunctionDeclaration) is more clear.
17474 if (New->getStorageClass() == SC_Static)
17475 return false;
17476
17477 Diag(New->getLocation(),
17478 diag::err_conflicting_overriding_cc_attributes)
17479 << New->getDeclName() << New->getType() << Old->getType();
17480 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17481 return true;
17482}
17483
17485 const CXXMethodDecl *Old) {
17486 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17487 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17488
17489 if (Context.hasSameType(NewTy, OldTy) ||
17490 NewTy->isDependentType() || OldTy->isDependentType())
17491 return false;
17492
17493 // Check if the return types are covariant
17494 QualType NewClassTy, OldClassTy;
17495
17496 /// Both types must be pointers or references to classes.
17497 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17498 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17499 NewClassTy = NewPT->getPointeeType();
17500 OldClassTy = OldPT->getPointeeType();
17501 }
17502 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17503 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17504 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17505 NewClassTy = NewRT->getPointeeType();
17506 OldClassTy = OldRT->getPointeeType();
17507 }
17508 }
17509 }
17510
17511 // The return types aren't either both pointers or references to a class type.
17512 if (NewClassTy.isNull()) {
17513 Diag(New->getLocation(),
17514 diag::err_different_return_type_for_overriding_virtual_function)
17515 << New->getDeclName() << NewTy << OldTy
17516 << New->getReturnTypeSourceRange();
17517 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17518 << Old->getReturnTypeSourceRange();
17519
17520 return true;
17521 }
17522
17523 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17524 // C++14 [class.virtual]p8:
17525 // If the class type in the covariant return type of D::f differs from
17526 // that of B::f, the class type in the return type of D::f shall be
17527 // complete at the point of declaration of D::f or shall be the class
17528 // type D.
17529 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17530 if (!RT->isBeingDefined() &&
17531 RequireCompleteType(New->getLocation(), NewClassTy,
17532 diag::err_covariant_return_incomplete,
17533 New->getDeclName()))
17534 return true;
17535 }
17536
17537 // Check if the new class derives from the old class.
17538 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17539 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17540 << New->getDeclName() << NewTy << OldTy
17541 << New->getReturnTypeSourceRange();
17542 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17543 << Old->getReturnTypeSourceRange();
17544 return true;
17545 }
17546
17547 // Check if we the conversion from derived to base is valid.
17548 if (CheckDerivedToBaseConversion(
17549 NewClassTy, OldClassTy,
17550 diag::err_covariant_return_inaccessible_base,
17551 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17553 New->getDeclName(), nullptr)) {
17554 // FIXME: this note won't trigger for delayed access control
17555 // diagnostics, and it's impossible to get an undelayed error
17556 // here from access control during the original parse because
17557 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17558 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17559 << Old->getReturnTypeSourceRange();
17560 return true;
17561 }
17562 }
17563
17564 // The qualifiers of the return types must be the same.
17565 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17566 Diag(New->getLocation(),
17567 diag::err_covariant_return_type_different_qualifications)
17568 << New->getDeclName() << NewTy << OldTy
17569 << New->getReturnTypeSourceRange();
17570 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17571 << Old->getReturnTypeSourceRange();
17572 return true;
17573 }
17574
17575
17576 // The new class type must have the same or less qualifiers as the old type.
17577 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17578 Diag(New->getLocation(),
17579 diag::err_covariant_return_type_class_type_more_qualified)
17580 << New->getDeclName() << NewTy << OldTy
17581 << New->getReturnTypeSourceRange();
17582 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17583 << Old->getReturnTypeSourceRange();
17584 return true;
17585 }
17586
17587 return false;
17588}
17589
17590/// Mark the given method pure.
17591///
17592/// \param Method the method to be marked pure.
17593///
17594/// \param InitRange the source range that covers the "0" initializer.
17596 SourceLocation EndLoc = InitRange.getEnd();
17597 if (EndLoc.isValid())
17598 Method->setRangeEnd(EndLoc);
17599
17600 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17601 Method->setPure();
17602 return false;
17603 }
17604
17605 if (!Method->isInvalidDecl())
17606 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17607 << Method->getDeclName() << InitRange;
17608 return true;
17609}
17610
17612 if (D->getFriendObjectKind())
17613 Diag(D->getLocation(), diag::err_pure_friend);
17614 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17615 CheckPureMethod(M, ZeroLoc);
17616 else
17617 Diag(D->getLocation(), diag::err_illegal_initializer);
17618}
17619
17620/// Determine whether the given declaration is a global variable or
17621/// static data member.
17622static bool isNonlocalVariable(const Decl *D) {
17623 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17624 return Var->hasGlobalStorage();
17625
17626 return false;
17627}
17628
17629/// Invoked when we are about to parse an initializer for the declaration
17630/// 'Dcl'.
17631///
17632/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17633/// static data member of class X, names should be looked up in the scope of
17634/// class X. If the declaration had a scope specifier, a scope will have
17635/// been created and passed in for this purpose. Otherwise, S will be null.
17637 // If there is no declaration, there was an error parsing it.
17638 if (!D || D->isInvalidDecl())
17639 return;
17640
17641 // We will always have a nested name specifier here, but this declaration
17642 // might not be out of line if the specifier names the current namespace:
17643 // extern int n;
17644 // int ::n = 0;
17645 if (S && D->isOutOfLine())
17646 EnterDeclaratorContext(S, D->getDeclContext());
17647
17648 // If we are parsing the initializer for a static data member, push a
17649 // new expression evaluation context that is associated with this static
17650 // data member.
17651 if (isNonlocalVariable(D))
17652 PushExpressionEvaluationContext(
17653 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17654}
17655
17656/// Invoked after we are finished parsing an initializer for the declaration D.
17658 // If there is no declaration, there was an error parsing it.
17659 if (!D || D->isInvalidDecl())
17660 return;
17661
17662 if (isNonlocalVariable(D))
17663 PopExpressionEvaluationContext();
17664
17665 if (S && D->isOutOfLine())
17666 ExitDeclaratorContext(S);
17667}
17668
17669/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17670/// C++ if/switch/while/for statement.
17671/// e.g: "if (int x = f()) {...}"
17673 // C++ 6.4p2:
17674 // The declarator shall not specify a function or an array.
17675 // The type-specifier-seq shall not contain typedef and shall not declare a
17676 // new class or enumeration.
17678 "Parser allowed 'typedef' as storage class of condition decl.");
17679
17680 Decl *Dcl = ActOnDeclarator(S, D);
17681 if (!Dcl)
17682 return true;
17683
17684 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17685 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17686 << D.getSourceRange();
17687 return true;
17688 }
17689
17690 return Dcl;
17691}
17692
17694 if (!ExternalSource)
17695 return;
17696
17698 ExternalSource->ReadUsedVTables(VTables);
17700 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17701 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17702 = VTablesUsed.find(VTables[I].Record);
17703 // Even if a definition wasn't required before, it may be required now.
17704 if (Pos != VTablesUsed.end()) {
17705 if (!Pos->second && VTables[I].DefinitionRequired)
17706 Pos->second = true;
17707 continue;
17708 }
17709
17710 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17711 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17712 }
17713
17714 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17715}
17716
17718 bool DefinitionRequired) {
17719 // Ignore any vtable uses in unevaluated operands or for classes that do
17720 // not have a vtable.
17721 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17722 CurContext->isDependentContext() || isUnevaluatedContext())
17723 return;
17724 // Do not mark as used if compiling for the device outside of the target
17725 // region.
17726 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17727 !isInOpenMPDeclareTargetContext() &&
17728 !isInOpenMPTargetExecutionDirective()) {
17729 if (!DefinitionRequired)
17730 MarkVirtualMembersReferenced(Loc, Class);
17731 return;
17732 }
17733
17734 // Try to insert this class into the map.
17735 LoadExternalVTableUses();
17736 Class = Class->getCanonicalDecl();
17737 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17738 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17739 if (!Pos.second) {
17740 // If we already had an entry, check to see if we are promoting this vtable
17741 // to require a definition. If so, we need to reappend to the VTableUses
17742 // list, since we may have already processed the first entry.
17743 if (DefinitionRequired && !Pos.first->second) {
17744 Pos.first->second = true;
17745 } else {
17746 // Otherwise, we can early exit.
17747 return;
17748 }
17749 } else {
17750 // The Microsoft ABI requires that we perform the destructor body
17751 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17752 // the deleting destructor is emitted with the vtable, not with the
17753 // destructor definition as in the Itanium ABI.
17754 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17755 CXXDestructorDecl *DD = Class->getDestructor();
17756 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17757 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17758 // If this is an out-of-line declaration, marking it referenced will
17759 // not do anything. Manually call CheckDestructor to look up operator
17760 // delete().
17761 ContextRAII SavedContext(*this, DD);
17762 CheckDestructor(DD);
17763 } else {
17764 MarkFunctionReferenced(Loc, Class->getDestructor());
17765 }
17766 }
17767 }
17768 }
17769
17770 // Local classes need to have their virtual members marked
17771 // immediately. For all other classes, we mark their virtual members
17772 // at the end of the translation unit.
17773 if (Class->isLocalClass())
17774 MarkVirtualMembersReferenced(Loc, Class);
17775 else
17776 VTableUses.push_back(std::make_pair(Class, Loc));
17777}
17778
17780 LoadExternalVTableUses();
17781 if (VTableUses.empty())
17782 return false;
17783
17784 // Note: The VTableUses vector could grow as a result of marking
17785 // the members of a class as "used", so we check the size each
17786 // time through the loop and prefer indices (which are stable) to
17787 // iterators (which are not).
17788 bool DefinedAnything = false;
17789 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17790 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17791 if (!Class)
17792 continue;
17795
17796 SourceLocation Loc = VTableUses[I].second;
17797
17798 bool DefineVTable = true;
17799
17800 // If this class has a key function, but that key function is
17801 // defined in another translation unit, we don't need to emit the
17802 // vtable even though we're using it.
17803 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17804 if (KeyFunction && !KeyFunction->hasBody()) {
17805 // The key function is in another translation unit.
17806 DefineVTable = false;
17808 KeyFunction->getTemplateSpecializationKind();
17811 "Instantiations don't have key functions");
17812 (void)TSK;
17813 } else if (!KeyFunction) {
17814 // If we have a class with no key function that is the subject
17815 // of an explicit instantiation declaration, suppress the
17816 // vtable; it will live with the explicit instantiation
17817 // definition.
17818 bool IsExplicitInstantiationDeclaration =
17820 for (auto R : Class->redecls()) {
17822 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17824 IsExplicitInstantiationDeclaration = true;
17825 else if (TSK == TSK_ExplicitInstantiationDefinition) {
17826 IsExplicitInstantiationDeclaration = false;
17827 break;
17828 }
17829 }
17830
17831 if (IsExplicitInstantiationDeclaration)
17832 DefineVTable = false;
17833 }
17834
17835 // The exception specifications for all virtual members may be needed even
17836 // if we are not providing an authoritative form of the vtable in this TU.
17837 // We may choose to emit it available_externally anyway.
17838 if (!DefineVTable) {
17839 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17840 continue;
17841 }
17842
17843 // Mark all of the virtual members of this class as referenced, so
17844 // that we can build a vtable. Then, tell the AST consumer that a
17845 // vtable for this class is required.
17846 DefinedAnything = true;
17847 MarkVirtualMembersReferenced(Loc, Class);
17848 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17849 if (VTablesUsed[Canonical])
17850 Consumer.HandleVTable(Class);
17851
17852 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17853 // no key function or the key function is inlined. Don't warn in C++ ABIs
17854 // that lack key functions, since the user won't be able to make one.
17855 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17856 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17858 const FunctionDecl *KeyFunctionDef = nullptr;
17859 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17860 KeyFunctionDef->isInlined()))
17861 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17862 }
17863 }
17864 VTableUses.clear();
17865
17866 return DefinedAnything;
17867}
17868
17870 const CXXRecordDecl *RD) {
17871 for (const auto *I : RD->methods())
17872 if (I->isVirtual() && !I->isPure())
17873 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17874}
17875
17877 const CXXRecordDecl *RD,
17878 bool ConstexprOnly) {
17879 // Mark all functions which will appear in RD's vtable as used.
17880 CXXFinalOverriderMap FinalOverriders;
17881 RD->getFinalOverriders(FinalOverriders);
17882 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17883 E = FinalOverriders.end();
17884 I != E; ++I) {
17885 for (OverridingMethods::const_iterator OI = I->second.begin(),
17886 OE = I->second.end();
17887 OI != OE; ++OI) {
17888 assert(OI->second.size() > 0 && "no final overrider");
17889 CXXMethodDecl *Overrider = OI->second.front().Method;
17890
17891 // C++ [basic.def.odr]p2:
17892 // [...] A virtual member function is used if it is not pure. [...]
17893 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17894 MarkFunctionReferenced(Loc, Overrider);
17895 }
17896 }
17897
17898 // Only classes that have virtual bases need a VTT.
17899 if (RD->getNumVBases() == 0)
17900 return;
17901
17902 for (const auto &I : RD->bases()) {
17903 const auto *Base =
17904 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17905 if (Base->getNumVBases() == 0)
17906 continue;
17907 MarkVirtualMembersReferenced(Loc, Base);
17908 }
17909}
17910
17911/// SetIvarInitializers - This routine builds initialization ASTs for the
17912/// Objective-C implementation whose ivars need be initialized.
17914 if (!getLangOpts().CPlusPlus)
17915 return;
17916 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17918 CollectIvarsToConstructOrDestruct(OID, ivars);
17919 if (ivars.empty())
17920 return;
17922 for (unsigned i = 0; i < ivars.size(); i++) {
17923 FieldDecl *Field = ivars[i];
17924 if (Field->isInvalidDecl())
17925 continue;
17926
17929 InitializationKind InitKind =
17930 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17931
17932 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17933 ExprResult MemberInit =
17934 InitSeq.Perform(*this, InitEntity, InitKind, None);
17935 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17936 // Note, MemberInit could actually come back empty if no initialization
17937 // is required (e.g., because it would call a trivial default constructor)
17938 if (!MemberInit.get() || MemberInit.isInvalid())
17939 continue;
17940
17941 Member =
17942 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17944 MemberInit.getAs<Expr>(),
17945 SourceLocation());
17946 AllToInit.push_back(Member);
17947
17948 // Be sure that the destructor is accessible and is marked as referenced.
17949 if (const RecordType *RecordTy =
17950 Context.getBaseElementType(Field->getType())
17951 ->getAs<RecordType>()) {
17952 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17953 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17954 MarkFunctionReferenced(Field->getLocation(), Destructor);
17955 CheckDestructorAccess(Field->getLocation(), Destructor,
17956 PDiag(diag::err_access_dtor_ivar)
17957 << Context.getBaseElementType(Field->getType()));
17958 }
17959 }
17960 }
17961 ObjCImplementation->setIvarInitializers(Context,
17962 AllToInit.data(), AllToInit.size());
17963 }
17964}
17965
17966static
17971 Sema &S) {
17972 if (Ctor->isInvalidDecl())
17973 return;
17974
17975 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17976
17977 // Target may not be determinable yet, for instance if this is a dependent
17978 // call in an uninstantiated template.
17979 if (Target) {
17980 const FunctionDecl *FNTarget = nullptr;
17981 (void)Target->hasBody(FNTarget);
17982 Target = const_cast<CXXConstructorDecl*>(
17983 cast_or_null<CXXConstructorDecl>(FNTarget));
17984 }
17985
17986 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17987 // Avoid dereferencing a null pointer here.
17988 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17989
17990 if (!Current.insert(Canonical).second)
17991 return;
17992
17993 // We know that beyond here, we aren't chaining into a cycle.
17994 if (!Target || !Target->isDelegatingConstructor() ||
17995 Target->isInvalidDecl() || Valid.count(TCanonical)) {
17996 Valid.insert(Current.begin(), Current.end());
17997 Current.clear();
17998 // We've hit a cycle.
17999 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18000 Current.count(TCanonical)) {
18001 // If we haven't diagnosed this cycle yet, do so now.
18002 if (!Invalid.count(TCanonical)) {
18003 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18004 diag::warn_delegating_ctor_cycle)
18005 << Ctor;
18006
18007 // Don't add a note for a function delegating directly to itself.
18008 if (TCanonical != Canonical)
18009 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18010
18012 while (C->getCanonicalDecl() != Canonical) {
18013 const FunctionDecl *FNTarget = nullptr;
18014 (void)C->getTargetConstructor()->hasBody(FNTarget);
18015 assert(FNTarget && "Ctor cycle through bodiless function");
18016
18017 C = const_cast<CXXConstructorDecl*>(
18018 cast<CXXConstructorDecl>(FNTarget));
18019 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18020 }
18021 }
18022
18023 Invalid.insert(Current.begin(), Current.end());
18024 Current.clear();
18025 } else {
18026 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18027 }
18028}
18029
18030
18033
18034 for (DelegatingCtorDeclsType::iterator
18035 I = DelegatingCtorDecls.begin(ExternalSource),
18036 E = DelegatingCtorDecls.end();
18037 I != E; ++I)
18038 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18039
18040 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18041 (*CI)->setInvalidDecl();
18042}
18043
18044namespace {
18045 /// AST visitor that finds references to the 'this' expression.
18046 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18047 Sema &S;
18048
18049 public:
18050 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18051
18052 bool VisitCXXThisExpr(CXXThisExpr *E) {
18053 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18054 << E->isImplicit();
18055 return false;
18056 }
18057 };
18058}
18059
18061 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18062 if (!TSInfo)
18063 return false;
18064
18065 TypeLoc TL = TSInfo->getTypeLoc();
18067 if (!ProtoTL)
18068 return false;
18069
18070 // C++11 [expr.prim.general]p3:
18071 // [The expression this] shall not appear before the optional
18072 // cv-qualifier-seq and it shall not appear within the declaration of a
18073 // static member function (although its type and value category are defined
18074 // within a static member function as they are within a non-static member
18075 // function). [ Note: this is because declaration matching does not occur
18076 // until the complete declarator is known. - end note ]
18077 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18078 FindCXXThisExpr Finder(*this);
18079
18080 // If the return type came after the cv-qualifier-seq, check it now.
18081 if (Proto->hasTrailingReturn() &&
18082 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18083 return true;
18084
18085 // Check the exception specification.
18086 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18087 return true;
18088
18089 // Check the trailing requires clause
18090 if (Expr *E = Method->getTrailingRequiresClause())
18091 if (!Finder.TraverseStmt(E))
18092 return true;
18093
18094 return checkThisInStaticMemberFunctionAttributes(Method);
18095}
18096
18098 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18099 if (!TSInfo)
18100 return false;
18101
18102 TypeLoc TL = TSInfo->getTypeLoc();
18104 if (!ProtoTL)
18105 return false;
18106
18107 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18108 FindCXXThisExpr Finder(*this);
18109
18110 switch (Proto->getExceptionSpecType()) {
18111 case EST_Unparsed:
18112 case EST_Uninstantiated:
18113 case EST_Unevaluated:
18114 case EST_BasicNoexcept:
18115 case EST_NoThrow:
18116 case EST_DynamicNone:
18117 case EST_MSAny:
18118 case EST_None:
18119 break;
18120
18122 case EST_NoexceptFalse:
18123 case EST_NoexceptTrue:
18124 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18125 return true;
18126 LLVM_FALLTHROUGH;
18127
18128 case EST_Dynamic:
18129 for (const auto &E : Proto->exceptions()) {
18130 if (!Finder.TraverseType(E))
18131 return true;
18132 }
18133 break;
18134 }
18135
18136 return false;
18137}
18138
18140 FindCXXThisExpr Finder(*this);
18141
18142 // Check attributes.
18143 for (const auto *A : Method->attrs()) {
18144 // FIXME: This should be emitted by tblgen.
18145 Expr *Arg = nullptr;
18146 ArrayRef<Expr *> Args;
18147 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18148 Arg = G->getArg();
18149 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18150 Arg = G->getArg();
18151 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18152 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18153 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18154 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18155 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18156 Arg = ETLF->getSuccessValue();
18157 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18158 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18159 Arg = STLF->getSuccessValue();
18160 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18161 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18162 Arg = LR->getArg();
18163 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18164 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18165 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18166 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18167 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18168 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18169 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18170 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18171 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18172 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18173
18174 if (Arg && !Finder.TraverseStmt(Arg))
18175 return true;
18176
18177 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18178 if (!Finder.TraverseStmt(Args[I]))
18179 return true;
18180 }
18181 }
18182
18183 return false;
18184}
18185
18187 bool IsTopLevel, ExceptionSpecificationType EST,
18188 ArrayRef<ParsedType> DynamicExceptions,
18189 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18190 SmallVectorImpl<QualType> &Exceptions,
18192 Exceptions.clear();
18193 ESI.Type = EST;
18194 if (EST == EST_Dynamic) {
18195 Exceptions.reserve(DynamicExceptions.size());
18196 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18197 // FIXME: Preserve type source info.
18198 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18199
18200 if (IsTopLevel) {
18202 collectUnexpandedParameterPacks(ET, Unexpanded);
18203 if (!Unexpanded.empty()) {
18205 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18206 Unexpanded);
18207 continue;
18208 }
18209 }
18210
18211 // Check that the type is valid for an exception spec, and
18212 // drop it if not.
18213 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18214 Exceptions.push_back(ET);
18215 }
18216 ESI.Exceptions = Exceptions;
18217 return;
18218 }
18219
18220 if (isComputedNoexcept(EST)) {
18221 assert((NoexceptExpr->isTypeDependent() ||
18222 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18223 Context.BoolTy) &&
18224 "Parser should have made sure that the expression is boolean");
18225 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18226 ESI.Type = EST_BasicNoexcept;
18227 return;
18228 }
18229
18230 ESI.NoexceptExpr = NoexceptExpr;
18231 return;
18232 }
18233}
18234
18237 SourceRange SpecificationRange,
18238 ArrayRef<ParsedType> DynamicExceptions,
18239 ArrayRef<SourceRange> DynamicExceptionRanges,
18240 Expr *NoexceptExpr) {
18241 if (!MethodD)
18242 return;
18243
18244 // Dig out the method we're referring to.
18245 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18246 MethodD = FunTmpl->getTemplatedDecl();
18247
18248 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18249 if (!Method)
18250 return;
18251
18252 // Check the exception specification.
18255 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18256 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18257 ESI);
18258
18259 // Update the exception specification on the function type.
18260 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18261
18262 if (Method->isStatic())
18263 checkThisInStaticMemberFunctionExceptionSpec(Method);
18264
18265 if (Method->isVirtual()) {
18266 // Check overrides, which we previously had to delay.
18267 for (const CXXMethodDecl *O : Method->overridden_methods())
18268 CheckOverridingFunctionExceptionSpec(Method, O);
18269 }
18270}
18271
18272/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18273///
18275 SourceLocation DeclStart, Declarator &D,
18276 Expr *BitWidth,
18277 InClassInitStyle InitStyle,
18278 AccessSpecifier AS,
18279 const ParsedAttr &MSPropertyAttr) {
18280 IdentifierInfo *II = D.getIdentifier();
18281 if (!II) {
18282 Diag(DeclStart, diag::err_anonymous_property);
18283 return nullptr;
18284 }
18286
18287 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18288 QualType T = TInfo->getType();
18289 if (getLangOpts().CPlusPlus) {
18290 CheckExtraCXXDefaultArguments(D);
18291
18292 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18293 UPPC_DataMemberType)) {
18294 D.setInvalidType();
18295 T = Context.IntTy;
18296 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18297 }
18298 }
18299
18300 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18301
18303 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18304 << getLangOpts().CPlusPlus17;
18307 diag::err_invalid_thread)
18309
18310 // Check to see if this name was declared as a member previously
18311 NamedDecl *PrevDecl = nullptr;
18312 LookupResult Previous(*this, II, Loc, LookupMemberName,
18313 ForVisibleRedeclaration);
18314 LookupName(Previous, S);
18315 switch (Previous.getResultKind()) {
18318 PrevDecl = Previous.getAsSingle<NamedDecl>();
18319 break;
18320
18322 PrevDecl = Previous.getRepresentativeDecl();
18323 break;
18324
18328 break;
18329 }
18330
18331 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18332 // Maybe we will complain about the shadowed template parameter.
18333 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18334 // Just pretend that we didn't see the previous declaration.
18335 PrevDecl = nullptr;
18336 }
18337
18338 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18339 PrevDecl = nullptr;
18340
18341 SourceLocation TSSL = D.getBeginLoc();
18342 MSPropertyDecl *NewPD =
18343 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18344 MSPropertyAttr.getPropertyDataGetter(),
18345 MSPropertyAttr.getPropertyDataSetter());
18346 ProcessDeclAttributes(TUScope, NewPD, D);
18347 NewPD->setAccess(AS);
18348
18349 if (NewPD->isInvalidDecl())
18350 Record->setInvalidDecl();
18351
18353 NewPD->setModulePrivate();
18354
18355 if (NewPD->isInvalidDecl() && PrevDecl) {
18356 // Don't introduce NewFD into scope; there's already something
18357 // with the same name in the same scope.
18358 } else if (II) {
18359 PushOnScopeChains(NewPD, S);
18360 } else
18361 Record->addDecl(NewPD);
18362
18363 return NewPD;
18364}
18365
18367 Declarator &Declarator, unsigned TemplateParameterDepth) {
18368 auto &Info = InventedParameterInfos.emplace_back();
18369 TemplateParameterList *ExplicitParams = nullptr;
18370 ArrayRef<TemplateParameterList *> ExplicitLists =
18372 if (!ExplicitLists.empty()) {
18373 bool IsMemberSpecialization, IsInvalid;
18374 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18376 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18377 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18378 /*SuppressDiagnostic=*/true);
18379 }
18380 if (ExplicitParams) {
18381 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18382 llvm::append_range(Info.TemplateParams, *ExplicitParams);
18383 Info.NumExplicitTemplateParams = ExplicitParams->size();
18384 } else {
18385 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18386 Info.NumExplicitTemplateParams = 0;
18387 }
18388}
18389
18391 auto &FSI = InventedParameterInfos.back();
18392 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18393 if (FSI.NumExplicitTemplateParams != 0) {
18394 TemplateParameterList *ExplicitParams =
18397 TemplateParameterList::Create(
18398 Context, ExplicitParams->getTemplateLoc(),
18399 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18400 ExplicitParams->getRAngleLoc(),
18401 ExplicitParams->getRequiresClause()));
18402 } else {
18404 TemplateParameterList::Create(
18405 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18406 SourceLocation(), /*RequiresClause=*/nullptr));
18407 }
18408 }
18409 InventedParameterInfos.pop_back();
18410}
Defines the clang::ASTContext interface.
#define V(N, I)
NodeId Parent
Definition ASTDiff.cpp:192
This file provides some common utility functions for processing Lambda related AST Constructs.
MatchType Type
DynTypedNode Node
StringRef P
auto * N
llvm::Error Error
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
int Category
Definition Format.cpp:2580
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
@ AR_accessible
@ AR_dependent
@ AR_inaccessible
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, ArrayRef< TemplateArgument > TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, Sema::InheritedConstructorInfo *ICI)
static bool RefersToRValueRef(Expr *MemRef)
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static void extendLeft(SourceRange &R, SourceRange Before)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static Expr * CastForMoving(Sema &SemaRef, Expr *E, QualType T=QualType())
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static const ParsedAttr * getMSPropertyAttr(const ParsedAttributesView &list)
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:209
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition ASTContext.h:663
QualType getRecordType(const RecordDecl *Decl) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
CanQualType LongDoubleTy
CanQualType Char16Ty
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
void Deallocate(void *Ptr) const
Definition ASTContext.h:739
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
CanQualType WideCharTy
IdentifierTable & Idents
Definition ASTContext.h:659
const LangOptions & getLangOpts() const
Definition ASTContext.h:790
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
QualType AutoDeductTy
CanQualType BoolTy
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:712
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType BuiltinFnTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
CanQualType Char32Ty
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:772
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isInvalid() const
Definition Ownership.h:165
bool isUsable() const
Definition Ownership.h:166
PtrTy get() const
Definition Ownership.h:169
bool isUnset() const
Definition Ownership.h:167
Wrapper for source info for arrays.
Definition TypeLoc.h:1519
TypeLoc getElementLoc() const
Definition TypeLoc.h:1549
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition Type.h:2955
QualType getElementType() const
Definition Type.h:2976
Attr - This represents one attribute.
Definition Attr.h:41
attr::Kind getKind() const
Definition Attr.h:81
bool isInherited() const
Definition Attr.h:90
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:88
@ AS_Keyword
__ptr16, alignas(...), etc.
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3317
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3395
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3037
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3387
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3046
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4207
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3807
Expr * getLHS() const
Definition Expr.h:3856
Expr * getRHS() const
Definition Expr.h:3858
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:4544
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:3947
Opcode getOpcode() const
Definition Expr.h:3851
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2049
A binding in a decomposition declaration.
Definition DeclCXX.h:3992
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition DeclCXX.cpp:3213
Wrapper for source info for block pointers.
Definition TypeLoc.h:1272
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:190
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:199
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:245
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition DeclCXX.h:189
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition DeclCXX.h:226
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Represents a call to a C++ constructor.
Definition ExprCXX.h:1460
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, ConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition ExprCXX.cpp:1034
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1611
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1532
Represents a C++ constructor within a class.
Definition DeclCXX.h:2437
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2679
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition DeclCXX.cpp:2669
ExplicitSpecifier getExplicitSpecifier()
Definition DeclCXX.h:2508
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2533
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:2646
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:2664
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2655
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2674
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2625
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2764
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2804
Represents a C++ base or member initializer.
Definition DeclCXX.h:2205
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2574
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2561
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1318
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.h:1336
Represents a C++ destructor within a class.
Definition DeclCXX.h:2701
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2759
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1651
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:177
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:669
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:1981
bool isVirtual() const
Definition DeclCXX.h:2025
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2073
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2448
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2442
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2432
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2096
bool isInstance() const
Definition DeclCXX.h:2008
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2402
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2201
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2126
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2066
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:82
Represents a C++ struct/union/class.
Definition DeclCXX.h:254
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition DeclCXX.h:1225
friend_range friends() const
Definition DeclFriend.h:247
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1296
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:573
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1195
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1494
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1321
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:982
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.h:1409
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:808
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:702
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1375
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1346
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1325
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:694
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:942
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1311
base_class_range bases()
Definition DeclCXX.h:596
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:566
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:999
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1256
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:754
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:873
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:891
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:638
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:542
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:912
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1685
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1218
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1233
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:954
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:561
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1169
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:590
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:685
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1237
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:1857
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition DeclCXX.cpp:676
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:1832
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1283
base_class_range vbases()
Definition DeclCXX.h:613
base_class_iterator vbases_begin()
Definition DeclCXX.h:620
ctor_range ctors() const
Definition DeclCXX.h:658
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:855
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1176
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1191
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:846
bool isDynamicClass() const
Definition DeclCXX.h:562
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1110
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:787
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1357
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1248
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1162
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:781
bool hasDefinition() const
Definition DeclCXX.h:549
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:897
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:988
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:1824
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition DeclCXX.h:883
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:975
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:1902
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1335
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:994
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1369
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1537
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:793
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:834
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:964
bool isInterfaceLike() const
Definition DeclCXX.cpp:1931
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:906
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1261
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1525
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:501
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:611
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:927
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:64
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:192
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:197
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:125
SourceRange getRange() const
Definition DeclSpec.h:69
SourceLocation getBeginLoc() const
Definition DeclSpec.h:73
bool isSet() const
Deprecated.
Definition DeclSpec.h:210
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:151
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:77
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:195
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:190
Represents the this expression in C++.
Definition ExprCXX.h:1142
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1156
bool isImplicit() const
Definition ExprCXX.h:1159
SourceLocation getLocation() const
Definition ExprCXX.h:1153
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:107
unsigned getNumHandlers() const
Definition StmtCXX.h:106
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2801
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:2992
bool isCallToStdMove() const
Definition Expr.cpp:3375
Expr * getCallee()
Definition Expr.h:2951
arg_range arguments()
Definition Expr.h:3040
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastKind getCastKind() const
Definition Expr.h:3519
Expr * getSubExpr()
Definition Expr.h:3525
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:179
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition Type.h:2659
QualType getElementType() const
Definition Type.h:2669
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1408
body_range body()
Definition Stmt.h:1464
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:381
ConditionalOperator - The ?: ternary operator.
Definition Expr.h:4145
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition Type.h:3003
const llvm::APInt & getSize() const
Definition Type.h:3024
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:28
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3498
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3561
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3019
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition DeclBase.h:1323
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2179
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1378
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:1904
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2028
bool isFileContext() const
Definition DeclBase.h:1974
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:1920
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:1979
bool isRecord() const
Definition DeclBase.h:1983
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2161
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2159
bool isFunctionOrMethod() const
Definition DeclBase.h:1956
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:1897
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1227
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:516
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:453
ValueDecl * getDecl()
Definition Expr.h:1295
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1419
Captures information about "declaration specifiers".
Definition DeclSpec.h:229
bool isVirtualSpecified() const
Definition DeclSpec.h:579
bool isModulePrivateSpecified() const
Definition DeclSpec.h:752
static const TST TST_typename
Definition DeclSpec.h:288
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:622
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:618
void ClearStorageClassSpecs()
Definition DeclSpec.h:454
TST getTypeSpecType() const
Definition DeclSpec.h:476
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:449
SCS getStorageClassSpec() const
Definition DeclSpec.h:440
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:507
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:506
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:548
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:585
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:750
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:441
ParsedAttributes & getAttributes()
Definition DeclSpec.h:796
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:549
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:586
Expr * getRepAsExpr() const
Definition DeclSpec.h:494
static const TST TST_enum
Definition DeclSpec.h:283
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:518
bool isInlineSpecified() const
Definition DeclSpec.h:568
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:550
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition DeclSpec.cpp:972
void ClearConstexprSpec()
Definition DeclSpec.h:764
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:542
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:450
Decl * getRepAsDecl() const
Definition DeclSpec.h:490
bool isFriendSpecified() const
Definition DeclSpec.h:749
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:552
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:580
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:759
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:514
static const TST TST_error
Definition DeclSpec.h:301
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:437
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:571
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:553
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:551
bool hasExplicitSpecifier() const
Definition DeclSpec.h:582
bool hasConstexprSpecifier() const
Definition DeclSpec.h:760
static const TST TST_auto
Definition DeclSpec.h:294
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1299
decl_range decls()
Definition Stmt.h:1347
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1325
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:83
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1015
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:428
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1174
T * getAttr() const
Definition DeclBase.h:545
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:415
void addAttr(Attr *A)
Definition DeclBase.cpp:887
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:565
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:101
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1123
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:132
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:86
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:459
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1167
@ FOK_None
Not a friend object.
Definition DeclBase.h:1165
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:218
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2584
bool isInvalidDecl() const
Definition DeclBase.h:560
unsigned getIdentifierNamespace() const
Definition DeclBase.h:843
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:475
SourceLocation getLocation() const
Definition DeclBase.h:432
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:141
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:201
void setLocalOwningModule(Module *M)
Definition DeclBase.h:784
void setImplicit(bool I=true)
Definition DeclBase.h:566
void setReferenced(bool R=true)
Definition DeclBase.h:595
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:444
DeclContext * getDeclContext()
Definition DeclBase.h:441
AccessSpecifier getAccess() const
Definition DeclBase.h:480
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:424
void dropAttr()
Definition DeclBase.h:520
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:872
bool hasAttr() const
Definition DeclBase.h:549
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:932
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:835
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:726
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:778
unsigned getNumTemplateParameterLists() const
Definition Decl.h:814
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:761
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:802
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:755
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1805
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2332
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2231
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition DeclSpec.cpp:325
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2274
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:1940
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2386
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2228
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2287
bool hasGroupingParens() const
Definition DeclSpec.h:2603
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2597
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2270
bool isRedeclaration() const
Definition DeclSpec.h:2643
DeclaratorContext getContext() const
Definition DeclSpec.h:1965
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:1961
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1976
bool isFunctionDefinition() const
Definition DeclSpec.h:2617
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:1959
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:1955
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2525
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2532
IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2222
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2103
bool isInvalidType() const
Definition DeclSpec.h:2598
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:1975
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2218
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:1947
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2363
A decomposition declaration.
Definition DeclCXX.h:4051
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4083
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1703
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1740
SourceRange getSourceRange() const
Definition DeclSpec.h:1748
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1746
Represents a C++17 deduced template specialization type.
Definition Type.h:5178
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2348
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2328
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2337
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:911
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2269
TypeLoc getNamedTypeLoc() const
Definition TypeLoc.h:2298
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2278
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5184
RAII object that enters a new expression evaluation context.
Definition Sema.h:13535
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3088
Represents an enum.
Definition Decl.h:3646
enumerator_range enumerators() const
Definition Decl.h:3779
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition Type.h:4732
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1828
const Expr * getExpr() const
Definition DeclCXX.h:1837
void setExpr(Expr *E)
Definition DeclCXX.h:1862
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1861
This represents one expression.
Definition Expr.h:109
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:168
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:185
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:2953
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition Expr.h:238
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:2949
bool isPRValue() const
Definition Expr.h:271
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:270
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3087
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:247
QualType getType() const
Definition Expr.h:141
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:2873
void setInClassInitializer(Expr *Init)
Set the C++11 in-class initializer for this member.
Definition Decl.h:3030
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3013
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.cpp:4324
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4271
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3006
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition Decl.h:3039
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.h:3020
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3065
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3076
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:71
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition Diagnostic.h:110
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:97
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:55
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:177
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups)
Definition Decl.cpp:2992
Represents a function declaration or definition.
Definition Decl.h:1874
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2537
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3097
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2592
bool isTrivialForCall() const
Definition Decl.h:2230
bool isPure() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2210
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2316
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3468
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:3783
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2171
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3614
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3266
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2644
QualType getReturnType() const
Definition Decl.h:2568
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2514
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2239
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2227
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:3897
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2522
void setWillHaveBody(bool V=true)
Definition Decl.h:2459
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3372
param_iterator param_begin()
Definition Decl.h:2526
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:2985
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2183
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2365
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:3913
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2611
void setTrivial(bool IT)
Definition Decl.h:2228
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:3734
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2310
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3284
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3129
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2639
void setTrivialForCall(bool IT)
Definition Decl.h:2231
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3041
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2235
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4112
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2656
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:3720
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2313
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4000
void setDefaulted(bool D=true)
Definition Decl.h:2236
bool isConsteval() const
Definition Decl.h:2322
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2250
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2585
DefaultedFunctionInfo * getDefaultedFunctionInfo() const
Definition Decl.cpp:3013
void setBody(Stmt *B)
Definition Decl.cpp:3109
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2201
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3486
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.h:2727
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3447
size_t param_size() const
Definition Decl.h:2530
void setDeletedAsWritten(bool D=true)
Definition Decl.h:2373
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3017
void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info)
Definition Decl.cpp:3004
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3064
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2622
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2545
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2458
Represents a prototype with parameter type info, e.g.
Definition Type.h:3962
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition Type.h:4370
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition Type.h:4192
unsigned getNumParams() const
Definition Type.h:4167
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition Type.h:4305
QualType getParamType(unsigned i) const
Definition Type.h:4169
bool isVariadic() const
Whether this function prototype is variadic.
Definition Type.h:4289
ExtProtoInfo getExtProtoInfo() const
Definition Type.h:4178
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition Type.h:4250
ArrayRef< QualType > getParamTypes() const
Definition Type.h:4174
ArrayRef< QualType > exceptions() const
Definition Type.h:4336
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition Type.h:4351
Declaration of a template function.
Wrapper for source info for functions.
Definition TypeLoc.h:1386
unsigned getNumParams() const
Definition TypeLoc.h:1458
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1465
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1467
ExtInfo withCallingConv(CallingConv cc) const
Definition Type.h:3844
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition Type.h:3618
CallingConv getCallConv() const
Definition Type.h:3891
QualType getReturnType() const
Definition Type.h:3880
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition Stmt.h:1938
Stmt * getThen()
Definition Stmt.h:2027
Stmt * getElse()
Definition Stmt.h:2036
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3622
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:1980
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5510
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3128
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3149
void setInherited(bool I)
Definition Attr.h:147
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2408
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2420
const TypeClass * getTypePtr() const
Definition TypeLoc.h:502
Describes an C or C++ initializer list.
Definition Expr.h:4791
unsigned getNumInits() const
Definition Expr.h:4821
const Expr * getInit(unsigned Init) const
Definition Expr.h:4839
child_range children()
Definition Expr.h:4978
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:900
An lvalue reference type, per C++11 [dcl.ref].
Definition Type.h:2867
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1866
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition ExprCXX.cpp:1218
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition ExprCXX.cpp:1222
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:2080
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:961
Represents a linkage specification.
Definition DeclCXX.h:2830
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:2876
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:2822
LanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:2839
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:643
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:680
Represents the results of name lookup.
Definition Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:580
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition Lookup.h:446
DeclClass * getAsSingle() const
Definition Lookup.h:533
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:452
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition Lookup.h:248
bool empty() const
Return true if no decls were found.
Definition Lookup.h:339
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:708
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:543
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition Lookup.h:288
bool isAmbiguous() const
Definition Lookup.h:301
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition Lookup.h:385
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:308
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:253
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:550
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:609
iterator end() const
Definition Lookup.h:336
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:335
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:233
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4120
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3277
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3168
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3247
Expr * getBase() const
Definition Expr.h:3241
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3359
Wrapper for source info for member pointers.
Definition TypeLoc.h:1290
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition Type.h:2903
Describes a module or submodule.
Definition Module.h:96
This represents a decl that may have a name.
Definition Decl.h:247
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:457
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:268
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:311
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:650
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:367
Represents a C++ namespace alias.
Definition DeclCXX.h:3020
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition DeclCXX.cpp:2933
Represent a C++ namespace.
Definition Decl.h:542
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition DeclCXX.cpp:2878
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:601
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition Decl.h:635
void setRBraceLoc(SourceLocation L)
Definition Decl.h:658
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2436
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2548
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Represents an ObjC class declaration.
Definition DeclObjC.h:1151
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1135
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:939
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:950
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1107
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:227
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4486
Represents a parameter to a function.
Definition Decl.h:1680
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:2879
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1809
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1797
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:2884
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:2904
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1713
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1801
bool hasInheritedDefaultArg() const
Definition Decl.h:1813
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2813
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:2909
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:2915
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1817
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2836
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:237
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:586
bool isDeclspecPropertyAttribute() const
Is this the Microsoft __declspec(property) attribute?
Definition ParsedAttr.h:460
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:580
static const ParsedAttributesView & none()
Definition ParsedAttr.h:916
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:996
Wrapper for source info for pointers.
Definition TypeLoc.h:1259
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition Type.h:2712
QualType getPointeeType() const
Definition Type.h:2722
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6102
llvm::iterator_range< semantics_iterator > semantics()
Definition Expr.h:6181
A (possibly-)qualified type.
Definition Type.h:731
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition Type.h:6629
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition Type.h:6634
QualType withConst() const
Definition Type.h:905
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition Type.h:972
void addConst()
Add the const type qualifier to this QualType.
Definition Type.h:902
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition Type.h:796
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition Type.h:6586
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition Type.h:1184
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition Type.h:6755
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition Type.h:6639
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition Type.h:858
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition Type.h:6726
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition Type.h:6618
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition Type.h:6592
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition Type.h:1079
bool hasNonTrivialObjCLifetime() const
Definition Type.h:1188
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2360
The collection of all-type qualifiers we support.
Definition Type.h:147
void addAddressSpace(LangAS space)
Definition Type.h:404
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition Type.h:178
void removeConst()
Definition Type.h:266
void removeAddressSpace()
Definition Type.h:403
void addConst()
Definition Type.h:267
LangAS getAddressSpace() const
Definition Type.h:378
An rvalue reference type, per C++11 [dcl.ref].
Definition Type.h:2885
Represents a struct/union/class.
Definition Decl.h:3919
bool hasFlexibleArrayMember() const
Definition Decl.h:3973
field_iterator field_end() const
Definition Decl.h:4148
field_range fields() const
Definition Decl.h:4145
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition Decl.cpp:4669
@ APK_CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:3944
@ APK_CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:3930
@ APK_CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:3939
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4130
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:3992
bool field_empty() const
Definition Decl.h:4153
field_iterator field_begin() const
Definition Decl.cpp:4703
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition Type.h:4706
RecordDecl * getDecl() const
Definition Type.h:4716
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:4674
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Base for LValueReferenceType and RValueReferenceType.
Definition Type.h:2823
QualType getPointeeType() const
Definition Type.h:2841
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:2794
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:40
void setEntity(DeclContext *E)
Definition Scope.h:365
void AddDecl(Decl *D)
Definition Scope.h:316
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:244
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:59
A RAII object to enter scope of a compound statement.
Definition Sema.h:4905
A RAII object to temporarily push a declaration context.
Definition Sema.h:991
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:3305
DefaultedComparisonKind asComparison() const
Definition Sema.h:3328
CXXSpecialMember asSpecialMember() const
Definition Sema.h:3327
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:6123
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:6165
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
A generic diagnostic builder for errors which may or may not be deferred.
Definition Sema.h:1733
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition Sema.h:1385
CXXMethodDecl * getMethod() const
Definition Sema.h:1401
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:1048
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:12516
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:355
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:1524
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:4165
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:4173
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition Sema.cpp:1860
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void CheckDelegatingCtorCycles()
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:46
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:696
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:409
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:1622
ExprResult ActOnCXXThis(SourceLocation loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
ASTContext & getASTContext() const
Definition Sema.h:1625
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:1527
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:3179
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
const LangOptions & getLangOpts() const
Definition Sema.h:1618
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
Preprocessor & PP
Definition Sema.h:408
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:620
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:407
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:839
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
ComparisonCategoryUsage
Definition Sema.h:5961
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamespaceDecl * lookupStdExperimentalNamespace()
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:626
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:421
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMember > SpecialMemberDecl
Definition Sema.h:1519
FriendDecl * CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo)
Perform semantic analysis of the given friend type declaration.
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition Sema.h:3292
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:3294
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:3297
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:9379
SourceManager & getSourceManager() const
Definition Sema.h:1623
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition Sema.h:7383
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:1419
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &)
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:2428
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_ErrorRecovery
Definition Sema.h:4403
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind)
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
ASTConsumer & Consumer
Definition Sema.h:410
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:114
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1124
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:411
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:4885
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
Decl * ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:296
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM)
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
AbstractDiagSelID
Definition Sema.h:7683
@ AbstractVariableType
Definition Sema.h:7687
@ AbstractReturnType
Definition Sema.h:7685
@ AbstractNone
Definition Sema.h:7684
@ AbstractFieldType
Definition Sema.h:7688
@ AbstractArrayType
Definition Sema.h:7691
@ AbstractParamType
Definition Sema.h:7686
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition SemaStmt.cpp:878
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition Sema.h:2876
CXXSpecialMember
Kinds of C++ special members.
Definition Sema.h:1508
@ CXXCopyConstructor
Definition Sema.h:1510
@ CXXMoveConstructor
Definition Sema.h:1511
@ CXXDestructor
Definition Sema.h:1514
@ CXXDefaultConstructor
Definition Sema.h:1509
@ CXXInvalid
Definition Sema.h:1515
@ CXXMoveAssignment
Definition Sema.h:1513
@ CXXCopyAssignment
Definition Sema.h:1512
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=None)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:409
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:6719
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed)
Definition DeclCXX.cpp:3195
Stmt - This represents one statement.
Definition Stmt.h:70
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:348
child_range children()
Definition Stmt.cpp:285
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:324
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:336
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1770
StringRef getString() const
Definition Expr.h:1850
bool isOrdinary() const
Definition Expr.h:1886
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3368
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3491
StringRef getKindName() const
Definition Decl.h:3559
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3471
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4394
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4388
bool isUnion() const
Definition Decl.h:3572
TagKind getTagKind() const
Definition Decl.h:3563
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3522
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1648
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition Type.h:5240
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
unsigned getIndex() const
Definition Type.h:4934
unsigned getDepth() const
Definition Type.h:4933
The top declaration context.
Definition Decl.h:82
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3340
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3358
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5139
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Represents a declaration of a type.
Definition Decl.h:3176
const Type * getTypeForDecl() const
Definition Decl.h:3200
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:58
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:132
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:169
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:88
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1183
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:77
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:152
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:158
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:115
bool isNull() const
Definition TypeLoc.h:120
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:228
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:191
A container of type source information.
Definition Type.h:6530
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:244
QualType getType() const
Return the type wrapped by this type source info.
Definition Type.h:6541
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition TypeLoc.h:516
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:2864
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition Type.h:5522
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:2851
The base class of the type hierarchy.
Definition Type.h:1556
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.cpp:1759
bool isVoidType() const
Definition Type.h:7096
bool isIncompleteArrayType() const
Definition Type.h:6881
bool isUndeducedAutoType() const
Definition Type.h:6952
bool isRValueReferenceType() const
Definition Type.h:6827
bool isArrayType() const
Definition Type.h:6873
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition Type.h:7128
const T * castAs() const
Member-template castAs<specific type>.
Definition Type.h:7369
bool isReferenceType() const
Definition Type.h:6819
bool isEnumeralType() const
Definition Type.h:6901
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:625
bool isLValueReferenceType() const
Definition Type.h:6823
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition Type.h:7065
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition Type.h:2244
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:1888
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition Type.h:1947
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition Type.h:7252
bool isFunctionProtoType() const
Definition Type.h:2088
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition Type.h:7225
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition Type.h:2262
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition Type.h:7218
bool isFunctionType() const
Definition Type.h:6803
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2137
const T * getAs() const
Member-template getAs<specific type>'.
Definition Type.h:7302
bool isRecordType() const
Definition Type.h:6897
bool isUnionType() const
Definition Type.cpp:595
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3218
QualType getUnderlyingType() const
Definition Decl.h:3273
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2165
Expr * getSubExpr() const
Definition Expr.h:2210
Opcode getOpcode() const
Definition Expr.h:2205
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2265
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:4601
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:951
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:987
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1163
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1160
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:995
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:998
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1033
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1003
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition ExprCXX.cpp:369
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
The iterator over UnresolvedSets.
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:3925
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3175
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:3844
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3155
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3747
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3127
Represents a C++ using-declaration.
Definition DeclCXX.h:3412
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3461
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3453
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3068
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3449
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3439
Represents C++ using-directive.
Definition DeclCXX.h:2915
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:2839
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3612
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, EnumDecl *ED)
Definition DeclCXX.cpp:3089
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3106
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3220
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3256
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3284
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3008
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:674
void setType(QualType newType)
Definition Decl.h:686
QualType getType() const
Definition Decl.h:685
Represents a variable declaration or definition.
Definition Decl.h:874
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2685
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2058
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1477
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2168
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2097
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition Decl.cpp:2711
bool isInlineSpecified() const
Definition Decl.h:1462
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2454
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1198
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1141
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1123
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1092
const Expr * getInit() const
Definition Decl.h:1283
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:897
void setInit(Expr *I)
Definition Decl.cpp:2362
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1083
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2408
void setExceptionVariable(bool EV)
Definition Decl.h:1405
Declaration of a variable template.
Represents a GCC generic vector type.
Definition Type.h:3301
unsigned getNumElements() const
Definition Type.h:3343
QualType getElementType() const
Definition Type.h:3342
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2658
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2678
SourceLocation getLastLocation() const
Definition DeclSpec.h:2690
bool isOverrideSpecified() const
Definition DeclSpec.h:2677
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2682
bool isFinalSpecified() const
Definition DeclSpec.h:2680
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2681
long int64_t
unsigned long uint64_t
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:56
const AstTypeMatcher< RecordType > recordType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Zero(InterpState &S, CodePtr OpPC)
Definition Interp.h:814
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:52
@ TST_decltype
Definition Specifiers.h:84
@ TST_decltype_auto
Definition Specifiers.h:87
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
bool isa(CodeGen::Address addr)
Definition Address.h:177
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:197
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:276
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:62
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:53
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:59
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:56
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:256
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:259
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:257
@ RQ_None
No ref-qualifier was provided.
Definition Type.h:1509
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:74
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:68
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:136
StorageClass
Storage classes.
Definition Specifiers.h:233
@ SC_Static
Definition Specifiers.h:237
@ SC_None
Definition Specifiers.h:235
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition Specifiers.h:220
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:272
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
StmtResult StmtError()
Definition Ownership.h:279
ActionResult< ParsedType > TypeResult
Definition Ownership.h:264
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition Type.h:5443
@ TTK_Class
The "class" keyword.
Definition Type.h:5454
@ TTK_Struct
The "struct" keyword.
Definition Type.h:5445
@ TTK_Interface
The "__interface" keyword.
Definition Type.h:5448
ExprResult ExprError()
Definition Ownership.h:278
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:117
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:120
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:129
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:124
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1229
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:173
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:191
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:187
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:183
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:179
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:176
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:263
U cast(CodeGen::Address addr)
Definition Address.h:174
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition Type.h:5462
@ ETK_None
No keyword precedes the qualified type name.
Definition Type.h:5483
Optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
bool isExternallyVisible(Linkage L)
Definition Linkage.h:91
ActionResult< Expr * > ExprResult
Definition Ownership.h:262
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:108
@ AS_public
Definition Specifiers.h:109
@ AS_protected
Definition Specifiers.h:110
@ AS_none
Definition Specifiers.h:112
@ AS_private
Definition Specifiers.h:111
ActionResult< Stmt * > StmtResult
Definition Ownership.h:263
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:162
#define true
Definition stdbool.h:21
#define false
Definition stdbool.h:22
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1286
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1341
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1293
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1344
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1442
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1316
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1474
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1380
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1467
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1262
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1174
enum clang::DeclaratorChunk::@209 Kind
FunctionTypeInfo Fun
Definition DeclSpec.h:1553
Holds information about the various types of exception specification.
Definition Type.h:4013
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition Type.h:4025
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition Type.h:4015
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition Type.h:4018
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition Type.h:4021
Extra information about a function prototype.
Definition Type.h:4039
FunctionType::ExtInfo ExtInfo
Definition Type.h:4040
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:965
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:8936
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:9041
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:9024
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:9021
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:8977
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:8995
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:9044
Abstract class used to diagnose incomplete types.
Definition Sema.h:2135
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:104